// 首页管理模块
class HomeManager {
    static loadContent(container) {
        container.innerHTML = `
            <div class="home-container">
                <div class="home-welcome">
                    <div class="welcome-icon">
                        <i class="fas fa-graduation-cap"></i>
                    </div>
                    <h1>欢迎使用智能陪练知识库管理系统</h1>
                    <p class="welcome-text">
                        这是一个功能强大的知识管理平台，帮助您高效组织和管理各类知识资源。
                        通过系统化的知识管理，为用户提供更好的学习和培训体验。
                    </p>
                    <div class="home-stats">
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-book"></i>
                            </div>
                            <div class="stat-content">
                                <h3>156</h3>
                                <p>知识资源</p>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-tags"></i>
                            </div>
                            <div class="stat-content">
                                <h3>28</h3>
                                <p>专题</p>
                            </div>
                        </div>
                    </div>
                    <div class="home-actions">
                        <button class="home-btn home-btn-primary" onclick="document.querySelector('[data-tab=\\'resource-library\\']').click()">
                            <i class="fas fa-plus-circle"></i> 开始管理知识
                        </button>
                    </div>
                </div>
            </div>
        `;
    }
}

// 知识库管理模块 - 资源库
class ResourceLibraryManager {
    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                管理系统知识资源库，包括文档、教程、指南等各类知识资源的创建、编辑、分类和管理。
            </div>

            <div class="actions">
                <button class="btn-primary btn-upload-resource"><i class="fas fa-upload"></i> 上传资源</button>
                <button class="btn btn-batch-upload"><i class="fas fa-file-archive"></i> 批量上传</button>
                <button class="btn btn-export"><i class="fas fa-file-export"></i> 导出</button>
                <button class="btn btn-submit-review" id="batchSubmitReviewBtn"><i class="fas fa-paper-plane"></i> 送审</button>
                <button class="btn btn-delete" id="batchDeleteBtn"><i class="fas fa-trash-alt"></i> 批量删除</button>
                <button class="btn btn-toggle-search" id="toggleAdvancedSearchBtn"><i class="fas fa-filter"></i> 高级筛选</button>
            </div>

            <!-- 高级搜索区域 -->
            <div class="advanced-search-panel" id="advancedSearchPanel" style="display: none;">
                <div class="search-panel-header">
                    <h3><i class="fas fa-search"></i> 高级搜索</h3>
                    <button class="btn-close-panel" id="closeSearchPanel"><i class="fas fa-times"></i></button>
                </div>
                <div class="search-panel-body">
                    <div class="search-form-row">
                        <div class="search-form-group">
                            <label>资源编号</label>
                            <input type="text" id="search_resourceId" class="form-control" placeholder="输入资源编号，支持模糊查询">
                        </div>
                        <div class="search-form-group">
                            <label>资源标题</label>
                            <input type="text" id="search_resourceTitle" class="form-control" placeholder="输入资源标题，支持模糊查询">
                        </div>
                    </div>

                    <div class="search-form-row">
                        <div class="search-form-group">
                            <label>资源类型</label>
                            <select id="search_resourceType" class="form-control">
                                <option value="">全部类型</option>
                                <option value="文档">文档</option>
                                <option value="视频">视频</option>
                                <option value="音频">音频</option>
                            </select>
                        </div>
                        <div class="search-form-group">
                            <label>所属专题</label>
                            <select id="search_topic" class="form-control">
                                <option value="">全部专题</option>
                                <option value="税务政策">税务政策</option>
                                <option value="话术培训">话术培训</option>
                                <option value="业务流程">业务流程</option>
                                <option value="客服技巧">客服技巧</option>
                                <option value="产品知识">产品知识</option>
                            </select>
                        </div>
                    </div>

                    <div class="search-form-row">
                        <div class="search-form-group">
                            <label>知识标签</label>
                            <select id="search_knowledgeTag" class="form-control">
                                <option value="">全部标签</option>
                                <option value="个税扣除">个税扣除</option>
                                <option value="专项附加">专项附加</option>
                                <option value="客服话术">客服话术</option>
                                <option value="税务咨询">税务咨询</option>
                                <option value="增值税">增值税</option>
                                <option value="政策改革">政策改革</option>
                                <option value="沟通技巧">沟通技巧</option>
                                <option value="话术模拟">话术模拟</option>
                            </select>
                        </div>
                        <div class="search-form-group">
                            <label>资源状态</label>
                            <select id="search_status" class="form-control">
                                <option value="">全部状态</option>
                                <option value="已发布">已发布</option>
                                <option value="草稿">草稿</option>
                                <option value="已下架">已下架</option>
                                <option value="待审核">待审核</option>
                            </select>
                        </div>
                    </div>

                    <div class="search-form-row">
                        <div class="search-form-group">
                            <label>更新时间</label>
                            <div class="date-range-group">
                                <input type="date" id="search_updateTimeStart" class="form-control">
                                <span class="date-separator">至</span>
                                <input type="date" id="search_updateTimeEnd" class="form-control">
                            </div>
                        </div>
                    </div>

                    <div class="search-form-row">
                        <div class="search-form-group">
                            <label>发布时间</label>
                            <div class="date-range-group">
                                <input type="date" id="search_publishTimeStart" class="form-control">
                                <span class="date-separator">至</span>
                                <input type="date" id="search_publishTimeEnd" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="search-panel-footer">
                    <button class="btn btn-secondary" id="resetSearchBtn"><i class="fas fa-redo"></i> 重置</button>
                    <button class="btn btn-primary" id="executeSearchBtn"><i class="fas fa-search"></i> 查询</button>
                </div>
            </div>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllResources"></th>
                            <th>资源编号</th>
                            <th>资源标题</th>
                            <th>资源类型</th>
                            <th>所属专题</th>
                            <th>知识点标签</th>
                            <th>上传人</th>
                            <th>状态</th>
                            <th>更新时间</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>RS001</td>
                            <td>2024个税专项附加扣除政策解读PPT</td>
                            <td><span class="resource-type-badge type-doc"><i class="fas fa-file-powerpoint"></i> 文档</span></td>
                            <td>税务政策</td>
                            <td><span class="tag">个税扣除</span></td>
                            <td>admin</td>
                            <td><span class="status-badge status-published"><i class="fas fa-check-circle"></i> 已发布</span></td>
                            <td>2024-01-15 10:30</td>
                            <td>2024-01-16 09:00</td>
                            <td class="operation">
                                <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('RS001'); return false;"><i class="fas fa-eye"></i></a>
                                <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('RS001'); return false;"><i class="fas fa-edit"></i></a>
                                <a href="#" title="下架" onclick="ResourceLibraryManager.changeStatus(this, 'RS001', '已下架'); return false;"><i class="fas fa-archive"></i></a>
                                <a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>RS002</td>
                            <td>税务咨询话术培训手册</td>
                            <td><span class="resource-type-badge type-doc"><i class="fas fa-file-word"></i> 文档</span></td>
                            <td>话术培训</td>
                            <td><span class="tag">客服话术</span></td>
                            <td>admin</td>
                            <td><span class="status-badge status-published"><i class="fas fa-check-circle"></i> 已发布</span></td>
                            <td>2024-01-10 14:20</td>
                            <td>2024-01-11 08:00</td>
                            <td class="operation">
                                <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('RS002'); return false;"><i class="fas fa-eye"></i></a>
                                <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('RS002'); return false;"><i class="fas fa-edit"></i></a>
                                <a href="#" title="下架" onclick="ResourceLibraryManager.changeStatus(this, 'RS002', '已下架'); return false;"><i class="fas fa-archive"></i></a>
                                <a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>RS003</td>
                            <td>政策解读视频-增值税改革</td>
                            <td><span class="resource-type-badge type-video"><i class="fas fa-file-video"></i> 视频</span></td>
                            <td>税务政策</td>
                            <td><span class="tag">增值税</span></td>
                            <td>admin</td>
                            <td><span class="status-badge status-draft"><i class="fas fa-file"></i> 草稿</span></td>
                            <td>2024-01-08 09:15</td>
                            <td>-</td>
                            <td class="operation">
                                <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('RS003'); return false;"><i class="fas fa-eye"></i></a>
                                <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('RS003'); return false;"><i class="fas fa-edit"></i></a>
                                <a href="#" title="发布" onclick="ResourceLibraryManager.changeStatus(this, 'RS003', '已发布'); return false;"><i class="fas fa-paper-plane"></i></a>
                                <a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>RS004</td>
                            <td>客服沟通技巧培训音频</td>
                            <td><span class="resource-type-badge type-audio"><i class="fas fa-file-audio"></i> 音频</span></td>
                            <td>客服技巧</td>
                            <td><span class="tag">沟通技巧</span></td>
                            <td>admin</td>
                            <td><span class="status-badge status-offline"><i class="fas fa-ban"></i> 已下架</span></td>
                            <td>2023-12-20 16:45</td>
                            <td>2023-12-21 10:00</td>
                            <td class="operation">
                                <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('RS004'); return false;"><i class="fas fa-eye"></i></a>
                                <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('RS004'); return false;"><i class="fas fa-edit"></i></a>
                                <a href="#" title="重新发布" onclick="ResourceLibraryManager.changeStatus(this, 'RS004', '已发布'); return false;"><i class="fas fa-redo"></i></a>
                                <a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">下一页</a>
            </div>
        `;

        // 设置全选功能
        const selectAll = container.querySelector('#selectAllResources');
        if (selectAll) {
            selectAll.addEventListener('change', function() {
                const checkboxes = container.querySelectorAll('.rowCheckbox');
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        }

        // 绑定上传按钮事件
        const uploadBtn = container.querySelector('.btn-upload-resource');
        if (uploadBtn) {
            uploadBtn.addEventListener('click', function() {
                ResourceLibraryManager.showUploadModal();
            });
        }

        // 绑定批量上传按钮事件
        const batchUploadBtn = container.querySelector('.btn-batch-upload');
        if (batchUploadBtn) {
            batchUploadBtn.addEventListener('click', function() {
                ResourceLibraryManager.showBatchUploadModal();
            });
        }

        // 绑定批量送审按钮事件
        const batchSubmitReviewBtn = container.querySelector('#batchSubmitReviewBtn');
        if (batchSubmitReviewBtn) {
            batchSubmitReviewBtn.addEventListener('click', function() {
                ResourceLibraryManager.batchSubmitReview(container);
            });
        }

        // 绑定批量删除按钮事件
        const batchDeleteBtn = container.querySelector('#batchDeleteBtn');
        if (batchDeleteBtn) {
            batchDeleteBtn.addEventListener('click', function() {
                ResourceLibraryManager.batchDelete(container);
            });
        }

        // 绑定高级筛选按钮事件
        const toggleAdvancedSearchBtn = container.querySelector('#toggleAdvancedSearchBtn');
        const advancedSearchPanel = container.querySelector('#advancedSearchPanel');
        const closeSearchPanel = container.querySelector('#closeSearchPanel');

        if (toggleAdvancedSearchBtn && advancedSearchPanel) {
            toggleAdvancedSearchBtn.addEventListener('click', function() {
                const isVisible = advancedSearchPanel.style.display !== 'none';
                advancedSearchPanel.style.display = isVisible ? 'none' : 'block';
                this.classList.toggle('active');
            });
        }

        if (closeSearchPanel && advancedSearchPanel) {
            closeSearchPanel.addEventListener('click', function() {
                advancedSearchPanel.style.display = 'none';
                toggleAdvancedSearchBtn.classList.remove('active');
            });
        }

        // 绑定查询按钮事件
        const executeSearchBtn = container.querySelector('#executeSearchBtn');
        if (executeSearchBtn) {
            executeSearchBtn.addEventListener('click', function() {
                ResourceLibraryManager.executeAdvancedSearch(container);
            });
        }

        // 绑定重置按钮事件
        const resetSearchBtn = container.querySelector('#resetSearchBtn');
        if (resetSearchBtn) {
            resetSearchBtn.addEventListener('click', function() {
                ResourceLibraryManager.resetSearchForm(container);
            });
        }
    }

    // 显示上传模态框
    static showUploadModal() {
        // 创建模态框HTML
        const modalHTML = `
            <div class="upload-modal" id="uploadModal">
                <div class="upload-modal-content">
                    <div class="upload-modal-header">
                        <h2><i class="fas fa-upload"></i> 上传资源</h2>
                        <button class="upload-modal-close" onclick="ResourceLibraryManager.closeUploadModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <!-- 资源元数据配置表单 -->
                        <div class="upload-form" id="uploadForm">
                            <!-- 核心信息卡片 -->
                            <div class="core-info-card">
                                <div class="core-info-header">
                                    <i class="fas fa-star"></i>
                                    <span>核心信息</span>
                                    <span class="required-badge">必填</span>
                                </div>

                                <div class="form-group highlighted">
                                    <label class="label-lg">
                                        <i class="fas fa-heading"></i> 资源标题
                                        <span class="required">*</span>
                                    </label>
                                    <input type="text" id="resourceTitle" class="form-control form-control-lg" placeholder="例如: 2024个税专项附加扣除政策解读PPT" maxlength="100">
                                    <div class="form-hint">请输入清晰的资源标题,便于检索和识别</div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group highlighted">
                                        <label class="label-lg">
                                            <i class="fas fa-folder-open"></i> 所属专题
                                            <span class="required">*</span>
                                        </label>
                                        <select id="resourceTopic" class="form-control form-control-lg">
                                            <option value="">请选择专题</option>
                                            <option value="税务政策">税务政策</option>
                                            <option value="话术培训">话术培训</option>
                                            <option value="业务流程">业务流程</option>
                                            <option value="客服技巧">客服技巧</option>
                                            <option value="产品知识">产品知识</option>
                                        </select>
                                    </div>

                                    <div class="form-group highlighted">
                                        <label class="label-lg">
                                            <i class="fas fa-lightbulb"></i> 知识点标签
                                            <span class="required">*</span>
                                        </label>
                                        <select id="coreKnowledge" class="form-control form-control-lg">
                                            <option value="">请选择知识点标签</option>
                                            <option value="个税扣除">个税扣除</option>
                                            <option value="专项附加">专项附加</option>
                                            <option value="客服话术">客服话术</option>
                                            <option value="税务咨询">税务咨询</option>
                                            <option value="增值税">增值税</option>
                                            <option value="政策改革">政策改革</option>
                                            <option value="沟通技巧">沟通技巧</option>
                                            <option value="话术模拟">话术模拟</option>
                                            <option value="政策解读">政策解读</option>
                                            <option value="业务流程">业务流程</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>资源类型 <span class="required">*</span></label>
                                    <select id="resourceType" class="form-control">
                                        <option value="">自动识别</option>
                                        <option value="文档">文档</option>
                                        <option value="视频">视频</option>
                                        <option value="音频">音频</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-section-title" style="margin-top: 25px;">
                                <i class="fas fa-list"></i> 扩展信息
                            </div>

                            <div class="form-group">
                                <label>资源描述</label>
                                <textarea id="resourceDesc" class="form-control" rows="3" placeholder="请输入资源描述,最多500字" maxlength="500"></textarea>
                                <div class="form-hint char-count">
                                    <span id="descCharCount">0</span>/500 字
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label>关联陪练场景</label>
                                    <select id="relatedScenario" class="form-control">
                                        <option value="">请选择场景</option>
                                        <option value="个税咨询-专项附加扣除">个税咨询 - 专项附加扣除</option>
                                        <option value="增值税申报">增值税申报</option>
                                        <option value="企业所得税">企业所得税</option>
                                        <option value="发票管理">发票管理</option>
                                        <option value="社保咨询">社保咨询</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>关联考试题库</label>
                                    <select id="relatedExam" class="form-control">
                                        <option value="">请选择题库</option>
                                        <option value="税务基础知识">税务基础知识</option>
                                        <option value="客服话术考核">客服话术考核</option>
                                        <option value="业务流程测试">业务流程测试</option>
                                        <option value="综合能力评估">综合能力评估</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-section-title" style="margin-top: 25px;">
                                <i class="fas fa-upload"></i> 文件上传
                            </div>

                            <!-- 上传区域 -->
                            <div class="upload-area" id="uploadArea">
                                <input type="file" id="fileInput" multiple style="display: none;" accept=".pdf,.doc,.docx,.ppt,.pptx,.mp4,.avi,.mov,.mp3,.wav">
                                <div class="upload-placeholder">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                    <h3>点击或拖拽文件到此处上传</h3>
                                    <p class="upload-hint">支持格式:</p>
                                    <div class="format-info">
                                        <div class="format-group">
                                            <strong>文档类:</strong> PDF、Word(.doc/.docx)、PPT(.ppt/.pptx)
                                            <br>单个文件 ≤ 50MB
                                        </div>
                                        <div class="format-group">
                                            <strong>音视频类:</strong> 视频(MP4/AVI/MOV)、音频(MP3/WAV)
                                            <br>视频 ≤ 200MB、音频 ≤ 50MB
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 文件列表 -->
                            <div class="upload-file-list" id="uploadFileList"></div>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-cancel" onclick="ResourceLibraryManager.closeUploadModal()">取消</button>
                        <div class="footer-right-buttons">
                            <button class="btn btn-secondary" id="saveDraftBtn" disabled>
                                <i class="fas fa-save"></i> 保存为草稿
                            </button>
                            <button class="btn btn-secondary" id="submitForReviewBtn" disabled>
                                <i class="fas fa-paper-plane"></i> 上传并送审
                            </button>
                            <button class="btn btn-primary" id="publishBtn" disabled>
                                <i class="fas fa-check-circle"></i> 发布
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 添加模态框到页面
        const existingModal = document.getElementById('uploadModal');
        if (existingModal) {
            existingModal.remove();
        }
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 初始化上传功能
        this.initUploadFeatures();
    }

    // 初始化上传功能
    static initUploadFeatures() {
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const uploadFileList = document.getElementById('uploadFileList');
        const saveDraftBtn = document.getElementById('saveDraftBtn');
        const submitForReviewBtn = document.getElementById('submitForReviewBtn');
        const publishBtn = document.getElementById('publishBtn');

        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', function(e) {
            if (e.target.closest('.upload-file-item')) return;
            fileInput.click();
        });

        // 文件选择事件
        fileInput.addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            ResourceLibraryManager.handleFiles(files);
        });

        // 拖拽上传功能
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('drag-over');
        });

        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
            const files = Array.from(e.dataTransfer.files);
            ResourceLibraryManager.handleFiles(files);
        });

        // 保存为草稿按钮
        saveDraftBtn.addEventListener('click', function() {
            ResourceLibraryManager.confirmUpload('草稿');
        });

        // 上传并送审按钮
        submitForReviewBtn.addEventListener('click', function() {
            ResourceLibraryManager.confirmUpload('待审核');
        });

        // 发布按钮
        publishBtn.addEventListener('click', function() {
            ResourceLibraryManager.confirmUpload('已发布');
        });

        // 资源描述字数统计
        const descTextarea = document.getElementById('resourceDesc');
        const charCount = document.getElementById('descCharCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 处理选择的文件
    static handleFiles(files) {
        const uploadFileList = document.getElementById('uploadFileList');
        const saveDraftBtn = document.getElementById('saveDraftBtn');
        const submitForReviewBtn = document.getElementById('submitForReviewBtn');
        const publishBtn = document.getElementById('publishBtn');

        if (files.length === 0) return;

        // 验证文件
        const validFiles = [];
        files.forEach(file => {
            const validation = this.validateFile(file);
            if (validation.valid) {
                validFiles.push(file);
            } else {
                alert(`文件 "${file.name}" ${validation.message}`);
            }
        });

        if (validFiles.length === 0) return;

        // 显示文件列表
        uploadFileList.innerHTML = '';
        validFiles.forEach((file, index) => {
            const fileItem = this.createFileItem(file, index);
            uploadFileList.insertAdjacentHTML('beforeend', fileItem);
        });

        // 启用上传按钮
        saveDraftBtn.disabled = false;
        submitForReviewBtn.disabled = false;
        publishBtn.disabled = false;

        // 保存文件列表到全局变量
        window.uploadedFiles = validFiles;
    }

    // 验证文件格式和大小
    static validateFile(file) {
        const fileName = file.name.toLowerCase();
        const fileSize = file.size;

        // 文档类
        const docExtensions = ['.pdf', '.doc', '.docx', '.ppt', '.pptx'];
        const docMaxSize = 50 * 1024 * 1024; // 50MB

        // 视频类
        const videoExtensions = ['.mp4', '.avi', '.mov'];
        const videoMaxSize = 200 * 1024 * 1024; // 200MB

        // 音频类
        const audioExtensions = ['.mp3', '.wav'];
        const audioMaxSize = 50 * 1024 * 1024; // 50MB

        // 检查文档类
        if (docExtensions.some(ext => fileName.endsWith(ext))) {
            if (fileSize > docMaxSize) {
                return { valid: false, message: '文档类文件大小不能超过50MB' };
            }
            return { valid: true };
        }

        // 检查视频类
        if (videoExtensions.some(ext => fileName.endsWith(ext))) {
            if (fileSize > videoMaxSize) {
                return { valid: false, message: '视频文件大小不能超过200MB' };
            }
            return { valid: true };
        }

        // 检查音频类
        if (audioExtensions.some(ext => fileName.endsWith(ext))) {
            if (fileSize > audioMaxSize) {
                return { valid: false, message: '音频文件大小不能超过50MB' };
            }
            return { valid: true };
        }

        return { valid: false, message: '不支持的文件格式' };
    }

    // 创建文件列表项
    static createFileItem(file, index) {
        const fileSize = this.formatFileSize(file.size);
        const fileIcon = this.getFileIcon(file.name);

        return `
            <div class="upload-file-item" data-index="${index}">
                <div class="file-icon">
                    <i class="fas ${fileIcon}"></i>
                </div>
                <div class="file-info">
                    <div class="file-name">${file.name}</div>
                    <div class="file-size">${fileSize}</div>
                </div>
                <div class="file-progress">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: 0%"></div>
                    </div>
                    <div class="progress-text">等待上传</div>
                </div>
                <button class="file-remove" onclick="ResourceLibraryManager.removeFile(${index})">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
    }

    // 获取文件图标
    static getFileIcon(fileName) {
        const ext = fileName.toLowerCase().split('.').pop();
        const iconMap = {
            'pdf': 'fa-file-pdf',
            'doc': 'fa-file-word',
            'docx': 'fa-file-word',
            'ppt': 'fa-file-powerpoint',
            'pptx': 'fa-file-powerpoint',
            'mp4': 'fa-file-video',
            'avi': 'fa-file-video',
            'mov': 'fa-file-video',
            'mp3': 'fa-file-audio',
            'wav': 'fa-file-audio'
        };
        return iconMap[ext] || 'fa-file';
    }

    // 格式化文件大小
    static formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 移除文件
    static removeFile(index) {
        if (!window.uploadedFiles) return;

        window.uploadedFiles.splice(index, 1);

        if (window.uploadedFiles.length === 0) {
            document.getElementById('uploadFileList').innerHTML = '';
            document.getElementById('saveDraftBtn').disabled = true;
            document.getElementById('submitForReviewBtn').disabled = true;
            document.getElementById('publishBtn').disabled = true;
        } else {
            this.handleFiles(window.uploadedFiles);
        }
    }

    // 确认上传
    static confirmUpload(status) {
        // 获取所有表单数据
        const title = document.getElementById('resourceTitle').value.trim();
        const topic = document.getElementById('resourceTopic').value;
        const resourceType = document.getElementById('resourceType').value;
        const coreKnowledge = document.getElementById('coreKnowledge').value;
        const desc = document.getElementById('resourceDesc').value.trim();
        const relatedScenario = document.getElementById('relatedScenario').value;
        const relatedExam = document.getElementById('relatedExam').value;

        // 验证必填项
        if (!title) {
            alert('请输入资源标题');
            document.getElementById('resourceTitle').focus();
            return;
        }
        if (!topic) {
            alert('请选择所属专题');
            document.getElementById('resourceTopic').focus();
            return;
        }
        if (!coreKnowledge) {
            alert('请选择知识点标签');
            document.getElementById('coreKnowledge').focus();
            return;
        }

        // 验证文件是否已上传
        if (!window.uploadedFiles || window.uploadedFiles.length === 0) {
            alert('请上传至少一个文件');
            document.getElementById('fileInput').focus();
            return;
        }

        // 收集元数据
        const metadata = {
            title,
            topic,
            resourceType: resourceType || '自动识别',
            coreKnowledge: coreKnowledge,
            desc,
            relatedScenario,
            relatedExam,
            resourceStatus: status,
            uploader: 'admin',
            uploadTime: new Date().toLocaleString()
        };

        console.log('上传元数据:', metadata);

        const statusMessage = status === '待审核' ? '资源已上传并提交审核' : status === '草稿' ? '资源已保存为草稿' : '资源已发布';

        // 模拟上传过程
        const fileItems = document.querySelectorAll('.upload-file-item');
        fileItems.forEach((item, index) => {
            const progressFill = item.querySelector('.progress-fill');
            const progressText = item.querySelector('.progress-text');

            // 模拟上传进度
            let progress = 0;
            const interval = setInterval(() => {
                progress += 10;
                progressFill.style.width = progress + '%';
                progressText.textContent = progress + '%';

                if (progress >= 100) {
                    clearInterval(interval);
                    progressText.textContent = '上传成功';
                    progressText.style.color = '#28a745';

                    // 最后一个文件上传完成后关闭模态框
                    if (index === fileItems.length - 1) {
                        setTimeout(() => {
                            alert(`${statusMessage}!\n标题: ${title}\n状态: ${status}`);
                            ResourceLibraryManager.closeUploadModal();
                            // 这里可以刷新资源列表
                        }, 500);
                    }
                }
            }, 200);
        });
    }

    // 关闭上传模态框
    static closeUploadModal() {
        const modal = document.getElementById('uploadModal');
        if (modal) {
            modal.remove();
        }
        window.uploadedFiles = null;
    }

    // ========== 批量上传功能 ==========

    // 显示批量上传模态框
    static showBatchUploadModal() {
        const modalHTML = `
            <div class="upload-modal" id="batchUploadModal">
                <div class="upload-modal-content batch-upload-content">
                    <div class="upload-modal-header">
                        <h2><i class="fas fa-file-archive"></i> 批量上传资源</h2>
                        <button class="upload-modal-close" onclick="ResourceLibraryManager.closeBatchUploadModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <!-- 上传区域 -->
                        <div class="upload-area" id="batchUploadArea">
                            <input type="file" id="batchFileInput" style="display: none;" accept=".zip,.rar">
                            <div class="upload-placeholder">
                                <i class="fas fa-file-archive"></i>
                                <h3>点击或拖拽压缩包到此处上传</h3>
                                <p class="upload-hint">支持批量上传压缩包</p>
                                <div class="format-info">
                                    <div class="format-group">
                                        <strong>支持格式:</strong> ZIP、RAR压缩包
                                        <br>压缩包大小 ≤ 500MB
                                    </div>
                                    <div class="format-group">
                                        <strong>自动处理:</strong> 解压后自动识别文件格式并分类存储
                                        <br>支持的文件类型: PDF、Word、PPT、视频、音频
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 上传的压缩包信息 -->
                        <div class="batch-file-info" id="batchFileInfo" style="display: none;">
                            <div class="batch-file-header">
                                <h3>压缩包信息</h3>
                                <button class="btn-secondary btn-sm" onclick="ResourceLibraryManager.clearBatchFile()">
                                    <i class="fas fa-redo"></i> 重新选择
                                </button>
                            </div>
                            <div class="batch-file-details" id="batchFileDetails"></div>
                        </div>

                        <!-- 解压后的文件列表 -->
                        <div class="extracted-files-section" id="extractedFilesSection" style="display: none;">
                            <div class="section-header">
                                <h3>解压文件列表</h3>
                                <div class="file-stats" id="fileStats"></div>
                            </div>

                            <!-- 文件校验结果 -->
                            <div class="validation-results" id="validationResults"></div>

                            <!-- 文件列表 -->
                            <div class="extracted-file-list" id="extractedFileList"></div>
                        </div>

                        <!-- 重复文件处理 -->
                        <div class="duplicate-files-section" id="duplicateFilesSection" style="display: none;">
                            <div class="section-header">
                                <h3><i class="fas fa-exclamation-triangle"></i> 发现重复文件</h3>
                            </div>
                            <div class="duplicate-file-list" id="duplicateFileList"></div>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-cancel" onclick="ResourceLibraryManager.closeBatchUploadModal()">取消</button>
                        <button class="btn btn-primary" id="startBatchUploadBtn" style="display: none;">开始上传</button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('batchUploadModal');
        if (existingModal) {
            existingModal.remove();
        }
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        this.initBatchUploadFeatures();
    }

    // 初始化批量上传功能
    static initBatchUploadFeatures() {
        const uploadArea = document.getElementById('batchUploadArea');
        const fileInput = document.getElementById('batchFileInput');

        // 点击上传区域
        uploadArea.addEventListener('click', function() {
            fileInput.click();
        });

        // 文件选择事件
        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                ResourceLibraryManager.handleBatchFile(file);
            }
        });

        // 拖拽功能
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('drag-over');
        });

        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
            const file = e.dataTransfer.files[0];
            if (file) {
                ResourceLibraryManager.handleBatchFile(file);
            }
        });

        // 开始上传按钮
        const startBtn = document.getElementById('startBatchUploadBtn');
        if (startBtn) {
            startBtn.addEventListener('click', function() {
                ResourceLibraryManager.startBatchUpload();
            });
        }
    }

    // 处理批量上传文件
    static handleBatchFile(file) {
        // 验证文件格式
        const fileName = file.name.toLowerCase();
        if (!fileName.endsWith('.zip') && !fileName.endsWith('.rar')) {
            alert('仅支持 ZIP 或 RAR 格式的压缩包');
            return;
        }

        // 验证文件大小
        const maxSize = 500 * 1024 * 1024; // 500MB
        if (file.size > maxSize) {
            alert('压缩包大小不能超过 500MB');
            return;
        }

        // 保存文件
        window.batchUploadFile = file;

        // 显示文件信息
        this.showBatchFileInfo(file);

        // 模拟解压和文件验证
        setTimeout(() => {
            this.simulateExtractAndValidate(file);
        }, 1000);
    }

    // 显示压缩包信息
    static showBatchFileInfo(file) {
        const uploadArea = document.getElementById('batchUploadArea');
        const fileInfo = document.getElementById('batchFileInfo');
        const fileDetails = document.getElementById('batchFileDetails');

        uploadArea.style.display = 'none';
        fileInfo.style.display = 'block';

        const fileSize = this.formatFileSize(file.size);
        fileDetails.innerHTML = `
            <div class="file-detail-item">
                <div class="file-icon-large">
                    <i class="fas fa-file-archive"></i>
                </div>
                <div class="file-detail-info">
                    <div class="file-detail-name">${file.name}</div>
                    <div class="file-detail-meta">
                        <span><i class="fas fa-hdd"></i> ${fileSize}</span>
                        <span><i class="fas fa-clock"></i> ${new Date(file.lastModified).toLocaleString()}</span>
                    </div>
                    <div class="file-status">
                        <div class="status-badge processing">
                            <i class="fas fa-spinner fa-spin"></i> 正在解压和验证...
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 模拟解压和验证
    static simulateExtractAndValidate(file) {
        // 模拟解压后的文件列表
        const extractedFiles = [
            { name: '税务政策2024.pdf', size: 2.5 * 1024 * 1024, type: 'pdf', valid: true },
            { name: '话术培训手册.docx', size: 1.8 * 1024 * 1024, type: 'docx', valid: true },
            { name: '培训课件.pptx', size: 5.2 * 1024 * 1024, type: 'pptx', valid: true },
            { name: '政策解读视频.mp4', size: 45 * 1024 * 1024, type: 'mp4', valid: true },
            { name: '服务示范音频.mp3', size: 3.5 * 1024 * 1024, type: 'mp3', valid: true },
            { name: '系统登录操作指南.pdf', size: 2.5 * 1024 * 1024, type: 'pdf', valid: true, duplicate: true }, // 重复文件
            { name: '可疑文件.exe', size: 1.2 * 1024 * 1024, type: 'exe', valid: false, error: '检测到可疑文件格式' },
        ];

        window.extractedFiles = extractedFiles;

        // 更新状态
        const statusBadge = document.querySelector('.status-badge');
        if (statusBadge) {
            statusBadge.className = 'status-badge success';
            statusBadge.innerHTML = '<i class="fas fa-check-circle"></i> 解压完成';
        }

        // 显示解压文件列表
        this.showExtractedFiles(extractedFiles);

        // 检查重复文件
        const duplicateFiles = extractedFiles.filter(f => f.duplicate);
        if (duplicateFiles.length > 0) {
            this.showDuplicateFiles(duplicateFiles);
        }
    }

    // 显示解压的文件列表
    static showExtractedFiles(files) {
        const section = document.getElementById('extractedFilesSection');
        const fileList = document.getElementById('extractedFileList');
        const fileStats = document.getElementById('fileStats');
        const validationResults = document.getElementById('validationResults');

        section.style.display = 'block';

        // 统计信息
        const validCount = files.filter(f => f.valid).length;
        const invalidCount = files.filter(f => !f.valid).length;
        const duplicateCount = files.filter(f => f.duplicate).length;

        fileStats.innerHTML = `
            <span class="stat-item stat-total"><i class="fas fa-files"></i> 总计: ${files.length}</span>
            <span class="stat-item stat-valid"><i class="fas fa-check"></i> 有效: ${validCount}</span>
            ${invalidCount > 0 ? `<span class="stat-item stat-invalid"><i class="fas fa-times"></i> 无效: ${invalidCount}</span>` : ''}
            ${duplicateCount > 0 ? `<span class="stat-item stat-duplicate"><i class="fas fa-exclamation-triangle"></i> 重复: ${duplicateCount}</span>` : ''}
        `;

        // 验证结果摘要
        if (invalidCount > 0) {
            validationResults.innerHTML = `
                <div class="validation-alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    发现 ${invalidCount} 个无效文件,这些文件将不会被上传
                </div>
            `;
        } else {
            validationResults.innerHTML = `
                <div class="validation-alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    所有文件验证通过
                </div>
            `;
        }

        // 文件列表
        fileList.innerHTML = files.map((file, index) => {
            const fileIcon = this.getFileIcon(file.name);
            const fileSize = this.formatFileSize(file.size);
            const statusClass = file.valid ? 'valid' : 'invalid';
            const statusIcon = file.valid ? 'fa-check-circle' : 'fa-times-circle';
            const statusText = file.valid ? '验证通过' : file.error;

            return `
                <div class="extracted-file-item ${statusClass}">
                    <div class="file-icon">
                        <i class="fas ${fileIcon}"></i>
                    </div>
                    <div class="file-info">
                        <div class="file-name">${file.name}</div>
                        <div class="file-meta">
                            <span>${fileSize}</span>
                            ${file.duplicate ? '<span class="duplicate-tag"><i class="fas fa-exclamation-triangle"></i> 重复文件</span>' : ''}
                        </div>
                    </div>
                    <div class="file-validation-status ${statusClass}">
                        <i class="fas ${statusIcon}"></i> ${statusText}
                    </div>
                </div>
            `;
        }).join('');

        // 显示上传按钮
        if (validCount > 0) {
            document.getElementById('startBatchUploadBtn').style.display = 'inline-flex';
        }
    }

    // 显示重复文件处理
    static showDuplicateFiles(duplicateFiles) {
        const section = document.getElementById('duplicateFilesSection');
        const fileList = document.getElementById('duplicateFileList');

        section.style.display = 'block';

        fileList.innerHTML = duplicateFiles.map((file, index) => `
            <div class="duplicate-file-item">
                <div class="duplicate-file-info">
                    <div class="file-icon">
                        <i class="fas ${this.getFileIcon(file.name)}"></i>
                    </div>
                    <div class="file-details">
                        <div class="file-name">${file.name}</div>
                        <div class="file-size">${this.formatFileSize(file.size)}</div>
                    </div>
                </div>
                <div class="duplicate-actions">
                    <label class="radio-option">
                        <input type="radio" name="duplicate_${index}" value="skip" checked>
                        <span>跳过</span>
                    </label>
                    <label class="radio-option">
                        <input type="radio" name="duplicate_${index}" value="overwrite">
                        <span>覆盖</span>
                    </label>
                    <label class="radio-option">
                        <input type="radio" name="duplicate_${index}" value="new_version">
                        <span>生成新版本</span>
                    </label>
                </div>
            </div>
        `).join('');
    }

    // 开始批量上传
    static startBatchUpload() {
        if (!window.extractedFiles) return;

        const validFiles = window.extractedFiles.filter(f => f.valid);

        // 处理重复文件选择
        const duplicateFiles = validFiles.filter(f => f.duplicate);
        duplicateFiles.forEach((file, index) => {
            const selected = document.querySelector(`input[name="duplicate_${index}"]:checked`);
            if (selected) {
                file.duplicateAction = selected.value;
            }
        });

        // 模拟上传进度
        const fileList = document.getElementById('extractedFileList');
        const fileItems = fileList.querySelectorAll('.extracted-file-item.valid');

        let uploadedCount = 0;
        fileItems.forEach((item, index) => {
            setTimeout(() => {
                item.classList.add('uploading');

                setTimeout(() => {
                    item.classList.remove('uploading');
                    item.classList.add('uploaded');
                    uploadedCount++;

                    if (uploadedCount === fileItems.length) {
                        setTimeout(() => {
                            alert(`批量上传完成!\n成功上传 ${uploadedCount} 个文件`);
                            ResourceLibraryManager.closeBatchUploadModal();
                        }, 500);
                    }
                }, 1000);
            }, index * 300);
        });

        // 禁用上传按钮
        document.getElementById('startBatchUploadBtn').disabled = true;
    }

    // 清除批量文件
    static clearBatchFile() {
        window.batchUploadFile = null;
        window.extractedFiles = null;

        document.getElementById('batchUploadArea').style.display = 'block';
        document.getElementById('batchFileInfo').style.display = 'none';
        document.getElementById('extractedFilesSection').style.display = 'none';
        document.getElementById('duplicateFilesSection').style.display = 'none';
        document.getElementById('startBatchUploadBtn').style.display = 'none';
    }

    // 关闭批量上传模态框
    static closeBatchUploadModal() {
        const modal = document.getElementById('batchUploadModal');
        if (modal) {
            modal.remove();
        }
        window.batchUploadFile = null;
        window.extractedFiles = null;
    }

    // ========== 资源详情和编辑 ==========

    // 显示资源详情模态框
    static showDetailModal(resourceId) {
        // 模拟数据
        const mockData = {
            'RS001': {
                title: '2024个税专项附加扣除政策解读PPT',
                id: 'RS001',
                uploader: 'admin',
                createTime: '2024-01-15 10:30',
                status: '已发布',
                type: '文档',
                typeIcon: 'fa-file-powerpoint',
                topic: '税务政策',
                fileSize: '5.2 MB',
                downloadCount: 128,
                knowledgePoints: ['个税扣除'],
                description: '本资源详细介绍了2024年个人所得税专项附加扣除的最新政策,包括子女教育、继续教育、大病医疗、住房贷款利息、住房租金、赡养老人等六大专项附加扣除项目。内容涵盖:<br><br>1. 各项扣除的标准和适用范围<br>2. 扣除凭证的准备要求<br>3. 申报流程和注意事项<br>4. 常见问题解答<br><br>适用于税务咨询人员进行客户服务时的政策讲解参考。',
                relatedScenario: '个税咨询 - 专项附加扣除',
                relatedExam: '税务基础知识',
                fileName: '2024个税专项附加扣除政策解读.pptx',
                version: 'v1.2.0'
            },
            'RS002': {
                title: '税务咨询话术培训手册',
                id: 'RS002',
                uploader: 'admin',
                createTime: '2024-01-10 14:20',
                status: '已发布',
                type: '文档',
                typeIcon: 'fa-file-word',
                topic: '话术培训',
                fileSize: '3.8 MB',
                downloadCount: 96,
                knowledgePoints: ['客服话术'],
                description: '专业的税务咨询话术培训手册,涵盖各类常见税务问题的应答技巧和标准话术模板。',
                relatedScenario: '税务咨询对话',
                relatedExam: '客服话术考核',
                fileName: '税务咨询话术培训手册.docx',
                version: 'v1.0.0'
            },
            'RS003': {
                title: '政策解读视频-增值税改革',
                id: 'RS003',
                uploader: 'admin',
                createTime: '2024-01-08 09:15',
                status: '草稿',
                type: '视频',
                typeIcon: 'fa-file-video',
                topic: '税务政策',
                fileSize: '125 MB',
                downloadCount: 0,
                knowledgePoints: ['增值税'],
                description: '详细解读最新增值税改革政策的视频教程。',
                relatedScenario: '增值税申报',
                relatedExam: '税务基础知识',
                fileName: '政策解读视频-增值税改革.mp4',
                version: 'v1.0.0'
            },
            'RS004': {
                title: '客服沟通技巧培训音频',
                id: 'RS004',
                uploader: 'admin',
                createTime: '2023-12-20 16:45',
                status: '已下架',
                type: '音频',
                typeIcon: 'fa-file-audio',
                topic: '客服技巧',
                fileSize: '15 MB',
                downloadCount: 45,
                knowledgePoints: ['沟通技巧'],
                description: '客服沟通技巧培训音频课程。',
                relatedScenario: '客服对话模拟',
                relatedExam: '客服话术考核',
                fileName: '客服沟通技巧培训.mp3',
                version: 'v1.1.0'
            }
        };

        const data = mockData[resourceId] || mockData['RS001'];

        const modalHTML = `
            <div class="upload-modal" id="detailModal">
                <div class="upload-modal-content" style="max-width: 900px;">
                    <div class="upload-modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                        <h2 style="color: white;"><i class="fas fa-eye"></i> 资源详情</h2>
                        <button class="upload-modal-close" onclick="ResourceLibraryManager.closeDetailModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body" style="max-height: 70vh; overflow-y: auto;">
                        <!-- 基本信息 -->
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-info-circle"></i> 基本信息</h3>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <label>资源标题:</label>
                                    <div>${data.title}</div>
                                </div>
                                <div class="detail-item">
                                    <label>资源编号:</label>
                                    <div>${data.id}</div>
                                </div>
                                <div class="detail-item">
                                    <label>资源类型:</label>
                                    <div><span class="resource-type-badge type-doc"><i class="fas ${data.typeIcon}"></i> ${data.type}</span></div>
                                </div>
                                <div class="detail-item">
                                    <label>所属专题:</label>
                                    <div>${data.topic}</div>
                                </div>
                                <div class="detail-item">
                                    <label>文件大小:</label>
                                    <div>${data.fileSize}</div>
                                </div>
                                <div class="detail-item">
                                    <label>上传人:</label>
                                    <div>${data.uploader}</div>
                                </div>
                                <div class="detail-item">
                                    <label>更新时间:</label>
                                    <div>${data.createTime}</div>
                                </div>
                            </div>
                        </div>

                        <!-- 知识点标签 -->
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-lightbulb"></i> 知识点标签</h3>
                            <div class="tag-list">
                                ${data.knowledgePoints.map(point => `<span class="tag">${point}</span>`).join('')}
                            </div>
                        </div>

                        <!-- 资源描述 -->
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-align-left"></i> 资源描述</h3>
                            <div class="detail-description">${data.description}</div>
                        </div>

                        <!-- 关联信息 -->
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-link"></i> 关联信息</h3>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <label>关联陪练场景:</label>
                                    <div>${data.relatedScenario}</div>
                                </div>
                                <div class="detail-item">
                                    <label>关联考试题库:</label>
                                    <div>${data.relatedExam}</div>
                                </div>
                            </div>
                        </div>

                        <!-- 文件信息 -->
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-file"></i> 文件信息</h3>
                            <div class="file-preview-box">
                                <div class="file-icon-large">
                                    <i class="fas ${data.typeIcon}"></i>
                                </div>
                                <div class="file-info-text">
                                    <div class="file-name">${data.fileName}</div>
                                    <div class="file-meta">大小: ${data.fileSize} • 版本: ${data.version}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-primary" onclick="ResourceLibraryManager.showEditModal('${data.id}'); ResourceLibraryManager.closeDetailModal();">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-success" onclick="alert('正在下载文件...')">
                            <i class="fas fa-download"></i> 下载文件
                        </button>
                        <button class="btn btn-cancel" onclick="ResourceLibraryManager.closeDetailModal()">关闭</button>
                    </div>
                </div>
            </div>
        `;

        // 添加模态框到页面
        const existingModal = document.getElementById('detailModal');
        if (existingModal) {
            existingModal.remove();
        }
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }

    // 关闭详情模态框
    static closeDetailModal() {
        const modal = document.getElementById('detailModal');
        if (modal) {
            modal.remove();
        }
    }

    // 显示编辑资源模态框
    static showEditModal(resourceId) {
        // 模拟数据
        const mockData = {
            'RS001': {
                title: '2024个税专项附加扣除政策解读PPT',
                id: 'RS001',
                topic: '税务政策',
                type: '文档',
                status: '已发布',
                knowledgePoints: ['个税扣除'],
                description: '本资源详细介绍了2024年个人所得税专项附加扣除的最新政策,包括子女教育、继续教育、大病医疗、住房贷款利息、住房租金、赡养老人等六大专项附加扣除项目。',
                relatedScenario: '个税咨询-专项附加扣除',
                relatedExam: '税务基础知识',
                fileName: '2024个税专项附加扣除政策解读.pptx'
            },
            'RS002': {
                title: '税务咨询话术培训手册',
                id: 'RS002',
                topic: '话术培训',
                type: '文档',
                status: '已发布',
                knowledgePoints: ['客服话术'],
                description: '专业的税务咨询话术培训手册。',
                relatedScenario: '税务咨询对话',
                relatedExam: '客服话术考核',
                fileName: '税务咨询话术培训手册.docx'
            },
            'RS003': {
                title: '政策解读视频-增值税改革',
                id: 'RS003',
                topic: '税务政策',
                type: '视频',
                status: '草稿',
                knowledgePoints: ['增值税'],
                description: '详细解读最新增值税改革政策的视频教程。',
                relatedScenario: '增值税申报',
                relatedExam: '税务基础知识',
                fileName: '政策解读视频-增值税改革.mp4'
            },
            'RS004': {
                title: '客服沟通技巧培训音频',
                id: 'RS004',
                topic: '客服技巧',
                type: '音频',
                status: '已下架',
                knowledgePoints: ['沟通技巧'],
                description: '客服沟通技巧培训音频课程。',
                relatedScenario: '客服对话模拟',
                relatedExam: '客服话术考核',
                fileName: '客服沟通技巧培训.mp3'
            }
        };

        const data = mockData[resourceId] || mockData['RS001'];

        const modalHTML = `
            <div class="upload-modal" id="editModal">
                <div class="upload-modal-content" style="max-width: 900px;">
                    <div class="upload-modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                        <h2 style="color: white;"><i class="fas fa-edit"></i> 编辑资源</h2>
                        <button class="upload-modal-close" onclick="ResourceLibraryManager.closeEditModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body" style="max-height: 65vh; overflow-y: auto;">
                        <form id="editResourceForm">
                            <!-- 基本信息 -->
                            <div class="form-section-title">
                                <i class="fas fa-info-circle"></i> 基本信息
                            </div>

                            <div class="form-group">
                                <label>资源标题 <span class="required">*</span></label>
                                <input type="text" id="edit_resourceTitle" class="form-control" value="${data.title}" required>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label>所属专题 <span class="required">*</span></label>
                                    <select id="edit_resourceTopic" class="form-control" required>
                                        <option value="">请选择专题</option>
                                        <option value="税务政策" ${data.topic === '税务政策' ? 'selected' : ''}>税务政策</option>
                                        <option value="话术培训" ${data.topic === '话术培训' ? 'selected' : ''}>话术培训</option>
                                        <option value="业务流程" ${data.topic === '业务流程' ? 'selected' : ''}>业务流程</option>
                                        <option value="客服技巧" ${data.topic === '客服技巧' ? 'selected' : ''}>客服技巧</option>
                                        <option value="产品知识" ${data.topic === '产品知识' ? 'selected' : ''}>产品知识</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>资源类型 <span class="required">*</span></label>
                                    <select id="edit_resourceType" class="form-control" required>
                                        <option value="文档" ${data.type === '文档' ? 'selected' : ''}>文档</option>
                                        <option value="视频" ${data.type === '视频' ? 'selected' : ''}>视频</option>
                                        <option value="音频" ${data.type === '音频' ? 'selected' : ''}>音频</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>资源状态 <span class="required">*</span></label>
                                <select id="edit_resourceStatus" class="form-control" required>
                                    <option value="已发布" ${data.status === '已发布' ? 'selected' : ''}>已发布</option>
                                    <option value="草稿" ${data.status === '草稿' ? 'selected' : ''}>草稿</option>
                                    <option value="已下架" ${data.status === '已下架' ? 'selected' : ''}>已下架</option>
                                </select>
                            </div>

                            <!-- 知识点标签 -->
                            <div class="form-section-title" style="margin-top: 25px;">
                                <i class="fas fa-lightbulb"></i> 知识点标签
                            </div>

                            <div class="form-group">
                                <label>知识点标签 <span class="required">*</span></label>
                                <select id="edit_coreKnowledge" class="form-control">
                                    <option value="">请选择知识点标签</option>
                                    <option value="个税扣除" ${data.knowledgePoints[0] === '个税扣除' ? 'selected' : ''}>个税扣除</option>
                                    <option value="专项附加" ${data.knowledgePoints[0] === '专项附加' ? 'selected' : ''}>专项附加</option>
                                    <option value="客服话术" ${data.knowledgePoints[0] === '客服话术' ? 'selected' : ''}>客服话术</option>
                                    <option value="税务咨询" ${data.knowledgePoints[0] === '税务咨询' ? 'selected' : ''}>税务咨询</option>
                                    <option value="增值税" ${data.knowledgePoints[0] === '增值税' ? 'selected' : ''}>增值税</option>
                                    <option value="政策改革" ${data.knowledgePoints[0] === '政策改革' ? 'selected' : ''}>政策改革</option>
                                    <option value="沟通技巧" ${data.knowledgePoints[0] === '沟通技巧' ? 'selected' : ''}>沟通技巧</option>
                                    <option value="话术模拟" ${data.knowledgePoints[0] === '话术模拟' ? 'selected' : ''}>话术模拟</option>
                                    <option value="政策解读" ${data.knowledgePoints[0] === '政策解读' ? 'selected' : ''}>政策解读</option>
                                    <option value="业务流程" ${data.knowledgePoints[0] === '业务流程' ? 'selected' : ''}>业务流程</option>
                                </select>
                            </div>

                            <!-- 资源描述 -->
                            <div class="form-section-title" style="margin-top: 25px;">
                                <i class="fas fa-align-left"></i> 资源描述
                            </div>

                            <div class="form-group">
                                <label>详细描述</label>
                                <textarea id="edit_resourceDescription" class="form-control" rows="4" maxlength="500">${data.description}</textarea>
                                <div class="form-hint char-count">
                                    <span id="edit_charCount">${data.description.length}</span>/500 字
                                </div>
                            </div>

                            <!-- 关联信息 -->
                            <div class="form-section-title" style="margin-top: 25px;">
                                <i class="fas fa-link"></i> 关联信息
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label>关联陪练场景</label>
                                    <select id="edit_relatedScenario" class="form-control">
                                        <option value="">请选择场景</option>
                                        <option value="个税咨询-专项附加扣除" ${data.relatedScenario === '个税咨询-专项附加扣除' ? 'selected' : ''}>个税咨询 - 专项附加扣除</option>
                                        <option value="增值税申报" ${data.relatedScenario === '增值税申报' ? 'selected' : ''}>增值税申报</option>
                                        <option value="税务咨询对话" ${data.relatedScenario === '税务咨询对话' ? 'selected' : ''}>税务咨询对话</option>
                                        <option value="客服对话模拟" ${data.relatedScenario === '客服对话模拟' ? 'selected' : ''}>客服对话模拟</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>关联考试题库</label>
                                    <select id="edit_relatedExam" class="form-control">
                                        <option value="">请选择题库</option>
                                        <option value="税务基础知识" ${data.relatedExam === '税务基础知识' ? 'selected' : ''}>税务基础知识</option>
                                        <option value="客服话术考核" ${data.relatedExam === '客服话术考核' ? 'selected' : ''}>客服话术考核</option>
                                        <option value="业务流程测试" ${data.relatedExam === '业务流程测试' ? 'selected' : ''}>业务流程测试</option>
                                    </select>
                                </div>
                            </div>

                            <input type="hidden" id="edit_resourceId" value="${data.id}">
                        </form>

                        <!-- 版本记录 -->
                        <div class="form-section-title" style="margin-top: 30px;">
                            <i class="fas fa-history"></i> 版本记录
                        </div>
                        <div class="version-history-container">
                            <table class="version-history-table">
                                <thead>
                                    <tr>
                                        <th>编辑时间</th>
                                        <th>编辑账号</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>2024-01-15 14:30:00</td>
                                        <td>admin</td>
                                    </tr>
                                    <tr>
                                        <td>2024-01-10 10:20:00</td>
                                        <td>admin</td>
                                    </tr>
                                    <tr>
                                        <td>2024-01-08 09:00:00</td>
                                        <td>admin</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-primary" onclick="ResourceLibraryManager.saveEditResource()">
                            <i class="fas fa-save"></i> 保存更改
                        </button>
                        <button class="btn btn-cancel" onclick="ResourceLibraryManager.closeEditModal()">取消</button>
                    </div>
                </div>
            </div>
        `;

        // 添加模态框到页面
        const existingModal = document.getElementById('editModal');
        if (existingModal) {
            existingModal.remove();
        }
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 初始化编辑功能
        this.initEditFeatures();
    }

    // 初始化编辑功能
    static initEditFeatures() {
        // 字符计数
        const descTextarea = document.getElementById('edit_resourceDescription');
        const charCount = document.getElementById('edit_charCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 保存编辑资源
    static saveEditResource() {
        const resourceId = document.getElementById('edit_resourceId').value;
        const title = document.getElementById('edit_resourceTitle').value.trim();
        const topic = document.getElementById('edit_resourceTopic').value;
        const type = document.getElementById('edit_resourceType').value;
        const status = document.getElementById('edit_resourceStatus').value;
        const description = document.getElementById('edit_resourceDescription').value;
        const relatedScenario = document.getElementById('edit_relatedScenario').value;
        const relatedExam = document.getElementById('edit_relatedExam').value;
        const coreKnowledge = document.getElementById('edit_coreKnowledge').value;

        if (!title) {
            alert('请输入资源标题');
            return;
        }

        if (!topic) {
            alert('请选择所属专题');
            return;
        }

        if (!coreKnowledge) {
            alert('请选择知识点标签');
            return;
        }

        const formData = {
            id: resourceId,
            title,
            topic,
            type,
            status,
            description,
            relatedScenario,
            relatedExam,
            coreKnowledge
        };

        console.log('保存数据:', formData);

        alert(`资源 ${resourceId} 已成功更新!`);
        this.closeEditModal();
    }

    // 关闭编辑模态框
    static closeEditModal() {
        const modal = document.getElementById('editModal');
        if (modal) {
            modal.remove();
        }
    }

    // ========== 批量操作 ==========

    // 批量送审
    static batchSubmitReview(container) {
        const checkedBoxes = container.querySelectorAll('.rowCheckbox:checked');

        if (checkedBoxes.length === 0) {
            alert('请至少选择一个资源进行送审');
            return;
        }

        const resourceIds = [];
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            const resourceId = row.cells[1].textContent;
            resourceIds.push(resourceId);
        });

        const confirmMsg = `确定要将选中的 ${resourceIds.length} 个资源送审吗?`;
        if (!confirm(confirmMsg)) return;

        // 模拟批量送审操作
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            const statusCell = row.cells[7];
            statusCell.innerHTML = '<span class="status-badge status-pending"><i class="fas fa-clock"></i> 待审核</span>';
            checkbox.checked = false;
        });

        // 取消全选
        const selectAll = container.querySelector('#selectAllResources');
        if (selectAll) selectAll.checked = false;

        alert(`已成功将 ${resourceIds.length} 个资源提交送审`);
    }

    // 批量删除
    static batchDelete(container) {
        const checkedBoxes = container.querySelectorAll('.rowCheckbox:checked');

        if (checkedBoxes.length === 0) {
            alert('请至少选择一个资源进行删除');
            return;
        }

        const resourceIds = [];
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            const resourceId = row.cells[1].textContent;
            resourceIds.push(resourceId);
        });

        const confirmMsg = `确定要删除选中的 ${resourceIds.length} 个资源吗?\n此操作不可恢复!`;
        if (!confirm(confirmMsg)) return;

        // 模拟批量删除操作
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            row.remove();
        });

        // 取消全选
        const selectAll = container.querySelector('#selectAllResources');
        if (selectAll) selectAll.checked = false;

        alert(`已成功删除 ${resourceIds.length} 个资源`);
    }

    // ========== 资源状态管理 ==========

    // 修改资源状态
    static changeStatus(element, resourceId, newStatus) {
        const statusMap = {
            '已发布': { icon: 'fa-check-circle', class: 'status-published', text: '已发布' },
            '草稿': { icon: 'fa-file', class: 'status-draft', text: '草稿' },
            '已下架': { icon: 'fa-ban', class: 'status-offline', text: '已下架' }
        };

        const statusInfo = statusMap[newStatus];
        if (!statusInfo) return;

        const confirmMsg = newStatus === '已下架'
            ? `确定要下架资源 ${resourceId} 吗?下架后该资源将不可见`
            : newStatus === '已发布'
            ? `确定要发布资源 ${resourceId} 吗?发布后全平台可见`
            : `确定要将资源 ${resourceId} 设为草稿吗?`;

        if (!confirm(confirmMsg)) return;

        // 查找状态单元格
        const row = element.closest('tr');
        const statusCell = row.cells[7]; // 状态列

        // 更新状态显示
        statusCell.innerHTML = `<span class="status-badge ${statusInfo.class}"><i class="fas ${statusInfo.icon}"></i> ${statusInfo.text}</span>`;

        // 更新操作按钮
        const operationCell = row.cells[10];
        this.updateOperationButtons(operationCell, resourceId, newStatus);

        alert(`资源状态已更新为: ${newStatus}`);
    }

    // 更新操作按钮
    static updateOperationButtons(operationCell, resourceId, status) {
        let buttons = `
            <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('${resourceId}'); return false;"><i class="fas fa-eye"></i></a>
            <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('${resourceId}'); return false;"><i class="fas fa-edit"></i></a>
        `;

        if (status === '已发布') {
            buttons += `<a href="#" title="下架" onclick="ResourceLibraryManager.changeStatus(this, '${resourceId}', '已下架'); return false;"><i class="fas fa-archive"></i></a>`;
        } else if (status === '草稿') {
            buttons += `<a href="#" title="发布" onclick="ResourceLibraryManager.changeStatus(this, '${resourceId}', '已发布'); return false;"><i class="fas fa-paper-plane"></i></a>`;
        } else if (status === '已下架') {
            buttons += `<a href="#" title="重新发布" onclick="ResourceLibraryManager.changeStatus(this, '${resourceId}', '已发布'); return false;"><i class="fas fa-redo"></i></a>`;
        }

        buttons += `<a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>`;

        operationCell.innerHTML = buttons;
    }

    // ========== 高级搜索功能 ==========

    // 执行高级搜索
    static executeAdvancedSearch(container) {
        // 获取搜索条件
        const searchCriteria = {
            resourceId: document.getElementById('search_resourceId')?.value.trim() || '',
            resourceTitle: document.getElementById('search_resourceTitle')?.value.trim() || '',
            resourceType: document.getElementById('search_resourceType')?.value || '',
            topic: document.getElementById('search_topic')?.value || '',
            knowledgeTag: document.getElementById('search_knowledgeTag')?.value || '',
            status: document.getElementById('search_status')?.value || '',
            updateTimeStart: document.getElementById('search_updateTimeStart')?.value || '',
            updateTimeEnd: document.getElementById('search_updateTimeEnd')?.value || '',
            publishTimeStart: document.getElementById('search_publishTimeStart')?.value || '',
            publishTimeEnd: document.getElementById('search_publishTimeEnd')?.value || ''
        };

        console.log('搜索条件:', searchCriteria);

        // 模拟搜索数据
        const allResources = [
            {
                id: 'RS001',
                title: '2024个税专项附加扣除政策解读PPT',
                type: '文档',
                typeIcon: 'fa-file-powerpoint',
                topic: '税务政策',
                tag: '个税扣除',
                uploader: 'admin',
                status: '已发布',
                statusClass: 'status-published',
                statusIcon: 'fa-check-circle',
                updateTime: '2024-01-15 10:30',
                publishTime: '2024-01-16 09:00'
            },
            {
                id: 'RS002',
                title: '税务咨询话术培训手册',
                type: '文档',
                typeIcon: 'fa-file-word',
                topic: '话术培训',
                tag: '客服话术',
                uploader: 'admin',
                status: '已发布',
                statusClass: 'status-published',
                statusIcon: 'fa-check-circle',
                updateTime: '2024-01-10 14:20',
                publishTime: '2024-01-11 08:00'
            },
            {
                id: 'RS003',
                title: '政策解读视频-增值税改革',
                type: '视频',
                typeIcon: 'fa-file-video',
                topic: '税务政策',
                tag: '增值税',
                uploader: 'admin',
                status: '草稿',
                statusClass: 'status-draft',
                statusIcon: 'fa-file',
                updateTime: '2024-01-08 09:15',
                publishTime: '-'
            },
            {
                id: 'RS004',
                title: '客服沟通技巧培训音频',
                type: '音频',
                typeIcon: 'fa-file-audio',
                topic: '客服技巧',
                tag: '沟通技巧',
                uploader: 'admin',
                status: '已下架',
                statusClass: 'status-offline',
                statusIcon: 'fa-ban',
                updateTime: '2023-12-20 16:45',
                publishTime: '2023-12-21 10:00'
            }
        ];

        // 筛选逻辑
        let filteredResources = allResources.filter(resource => {
            // 资源编号模糊查询
            if (searchCriteria.resourceId && !resource.id.toLowerCase().includes(searchCriteria.resourceId.toLowerCase())) {
                return false;
            }

            // 资源标题模糊查询
            if (searchCriteria.resourceTitle && !resource.title.toLowerCase().includes(searchCriteria.resourceTitle.toLowerCase())) {
                return false;
            }

            // 资源类型精确匹配
            if (searchCriteria.resourceType && resource.type !== searchCriteria.resourceType) {
                return false;
            }

            // 所属专题精确匹配
            if (searchCriteria.topic && resource.topic !== searchCriteria.topic) {
                return false;
            }

            // 知识标签匹配
            if (searchCriteria.knowledgeTag && resource.tag !== searchCriteria.knowledgeTag) {
                return false;
            }

            // 资源状态精确匹配
            if (searchCriteria.status && resource.status !== searchCriteria.status) {
                return false;
            }

            // 更新时间范围查询
            if (searchCriteria.updateTimeStart || searchCriteria.updateTimeEnd) {
                const updateTime = new Date(resource.updateTime);
                if (searchCriteria.updateTimeStart) {
                    const startTime = new Date(searchCriteria.updateTimeStart);
                    if (updateTime < startTime) return false;
                }
                if (searchCriteria.updateTimeEnd) {
                    const endTime = new Date(searchCriteria.updateTimeEnd);
                    endTime.setHours(23, 59, 59, 999);
                    if (updateTime > endTime) return false;
                }
            }

            // 发布时间范围查询
            if (searchCriteria.publishTimeStart || searchCriteria.publishTimeEnd) {
                if (resource.publishTime === '-') return false;
                const publishTime = new Date(resource.publishTime);
                if (searchCriteria.publishTimeStart) {
                    const startTime = new Date(searchCriteria.publishTimeStart);
                    if (publishTime < startTime) return false;
                }
                if (searchCriteria.publishTimeEnd) {
                    const endTime = new Date(searchCriteria.publishTimeEnd);
                    endTime.setHours(23, 59, 59, 999);
                    if (publishTime > endTime) return false;
                }
            }

            return true;
        });

        console.log('筛选结果:', filteredResources);

        // 更新表格显示
        this.updateResourceTable(container, filteredResources);

        // 显示搜索结果提示
        alert(`搜索完成！找到 ${filteredResources.length} 条匹配的资源`);
    }

    // 更新资源表格
    static updateResourceTable(container, resources) {
        const tbody = container.querySelector('table tbody');
        if (!tbody) return;

        if (resources.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="11" style="text-align: center; padding: 40px; color: #999;">
                        <i class="fas fa-search" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                        未找到符合条件的资源
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = resources.map(resource => {
            const actionButtons = resource.status === '已发布'
                ? `<a href="#" title="下架" onclick="ResourceLibraryManager.changeStatus(this, '${resource.id}', '已下架'); return false;"><i class="fas fa-archive"></i></a>`
                : resource.status === '草稿'
                ? `<a href="#" title="发布" onclick="ResourceLibraryManager.changeStatus(this, '${resource.id}', '已发布'); return false;"><i class="fas fa-paper-plane"></i></a>`
                : `<a href="#" title="重新发布" onclick="ResourceLibraryManager.changeStatus(this, '${resource.id}', '已发布'); return false;"><i class="fas fa-redo"></i></a>`;

            return `
                <tr>
                    <td><input type="checkbox" class="rowCheckbox"></td>
                    <td>${resource.id}</td>
                    <td>${resource.title}</td>
                    <td><span class="resource-type-badge type-doc"><i class="fas ${resource.typeIcon}"></i> ${resource.type}</span></td>
                    <td>${resource.topic}</td>
                    <td><span class="tag">${resource.tag}</span></td>
                    <td>${resource.uploader}</td>
                    <td><span class="status-badge ${resource.statusClass}"><i class="fas ${resource.statusIcon}"></i> ${resource.status}</span></td>
                    <td>${resource.updateTime}</td>
                    <td>${resource.publishTime}</td>
                    <td class="operation">
                        <a href="#" title="查看详情" onclick="ResourceLibraryManager.showDetailModal('${resource.id}'); return false;"><i class="fas fa-eye"></i></a>
                        <a href="#" title="编辑" onclick="ResourceLibraryManager.showEditModal('${resource.id}'); return false;"><i class="fas fa-edit"></i></a>
                        ${actionButtons}
                        <a href="#" title="删除" class="text-danger"><i class="fas fa-trash"></i></a>
                    </td>
                </tr>
            `;
        }).join('');
    }

    // 重置搜索表单
    static resetSearchForm(container) {
        document.getElementById('search_resourceId').value = '';
        document.getElementById('search_resourceTitle').value = '';
        document.getElementById('search_resourceType').value = '';
        document.getElementById('search_topic').value = '';
        document.getElementById('search_knowledgeTag').value = '';
        document.getElementById('search_status').value = '';
        document.getElementById('search_updateTimeStart').value = '';
        document.getElementById('search_updateTimeEnd').value = '';
        document.getElementById('search_publishTimeStart').value = '';
        document.getElementById('search_publishTimeEnd').value = '';

        alert('搜索条件已重置');

        // 重新加载全部资源
        this.executeAdvancedSearch(container);
    }
}


// 知识库管理模块 - 专题管理
class TopicManagementManager {
    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                管理知识专题，将相关知识内容按主题进行组织和归类，便于系统化学习。
            </div>

            <div class="actions">
                <button class="btn-primary btn-add-topic"><i class="fas fa-plus"></i> 新增专题</button>
                <button class="btn btn-batch-import"><i class="fas fa-file-import"></i> 批量导入</button>
                <button class="btn btn-export"><i class="fas fa-file-export"></i> 导出</button>
                <button class="btn btn-delete" id="batchDeleteTopicsBtn"><i class="fas fa-trash-alt"></i> 批量删除</button>
            </div>

            <!-- 查询条件区域 -->
            <div class="topic-search-area">
                <div class="search-form-row">
                    <div class="search-form-group">
                        <label>专题编号</label>
                        <input type="text" id="topic_search_id" class="form-control" placeholder="输入专题编号，支持模糊查询">
                    </div>
                    <div class="search-form-group">
                        <label>专题名称</label>
                        <input type="text" id="topic_search_name" class="form-control" placeholder="输入专题名称，支持模糊查询">
                    </div>
                    <div class="search-form-group">
                        <label>创建人</label>
                        <input type="text" id="topic_search_creator" class="form-control" placeholder="输入创建人">
                    </div>
                </div>

                <div class="search-form-row">
                    <div class="search-form-group">
                        <label>更新时间</label>
                        <div class="date-range-group">
                            <input type="date" id="topic_search_updateTimeStart" class="form-control">
                            <span class="date-separator">至</span>
                            <input type="date" id="topic_search_updateTimeEnd" class="form-control">
                        </div>
                    </div>
                    <div class="search-form-group search-actions">
                        <button class="btn btn-primary" id="topicSearchBtn"><i class="fas fa-search"></i> 查询</button>
                        <button class="btn btn-secondary" id="topicResetBtn"><i class="fas fa-redo"></i> 重置</button>
                    </div>
                </div>
            </div>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllTopics"></th>
                            <th>专题编号</th>
                            <th>专题名称</th>
                            <th>专题描述</th>
                            <th>包含资源数</th>
                            <th>浏览次数</th>
                            <th>创建人</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>TP001</td>
                            <td>税务政策</td>
                            <td>税务政策类内容</td>
                            <td>15</td>
                            <td>1234</td>
                            <td>admin</td>
                            <td>2024-01-15 10:30:00</td>
                            <td class="operation">
                                <a href="#" onclick="TopicManagementManager.showDetailModal('TP001'); return false;"><i class="fas fa-eye"></i> 查看</a>
                                <a href="#" onclick="TopicManagementManager.showEditModal('TP001'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" onclick="TopicManagementManager.deleteTopic('TP001'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>TP002</td>
                            <td>话术培训</td>
                            <td>坐席话务接听培训</td>
                            <td>23</td>
                            <td>856</td>
                            <td>admin</td>
                            <td>2024-01-12 14:20:00</td>
                            <td class="operation">
                                <a href="#" onclick="TopicManagementManager.showDetailModal('TP002'); return false;"><i class="fas fa-eye"></i> 查看</a>
                                <a href="#" onclick="TopicManagementManager.showEditModal('TP002'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" onclick="TopicManagementManager.deleteTopic('TP002'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">下一页</a>
            </div>
        `;

        // 设置全选功能
        const selectAll = container.querySelector('#selectAllTopics');
        if (selectAll) {
            selectAll.addEventListener('change', function() {
                const checkboxes = container.querySelectorAll('.rowCheckbox');
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        }

        // 绑定新增专题按钮
        const addTopicBtn = container.querySelector('.btn-add-topic');
        if (addTopicBtn) {
            addTopicBtn.addEventListener('click', function() {
                TopicManagementManager.showAddModal();
            });
        }

        // 绑定批量导入按钮
        const batchImportBtn = container.querySelector('.btn-batch-import');
        if (batchImportBtn) {
            batchImportBtn.addEventListener('click', function() {
                TopicManagementManager.showBatchImportModal();
            });
        }

        // 绑定批量删除按钮
        const batchDeleteBtn = container.querySelector('#batchDeleteTopicsBtn');
        if (batchDeleteBtn) {
            batchDeleteBtn.addEventListener('click', function() {
                TopicManagementManager.batchDelete(container);
            });
        }

        // 绑定查询按钮
        const topicSearchBtn = container.querySelector('#topicSearchBtn');
        if (topicSearchBtn) {
            topicSearchBtn.addEventListener('click', function() {
                TopicManagementManager.executeTopicSearch(container);
            });
        }

        // 绑定重置按钮
        const topicResetBtn = container.querySelector('#topicResetBtn');
        if (topicResetBtn) {
            topicResetBtn.addEventListener('click', function() {
                TopicManagementManager.resetTopicSearch(container);
            });
        }
    }

    // 显示新增专题模态框
    static showAddModal() {
        const modalHTML = `
            <div class="upload-modal" id="addTopicModal">
                <div class="upload-modal-content" style="max-width: 800px;">
                    <div class="upload-modal-header">
                        <h2><i class="fas fa-plus-circle"></i> 新增专题</h2>
                        <button class="upload-modal-close" onclick="TopicManagementManager.closeAddModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <form id="addTopicForm">
                            <div class="form-section-title">
                                <i class="fas fa-info-circle"></i> 基本信息
                            </div>

                            <div class="form-group">
                                <label>专题名称 <span class="required">*</span></label>
                                <input type="text" id="add_topicName" class="form-control" placeholder="请输入专题名称" required>
                            </div>

                            <div class="form-group">
                                <label>专题描述 <span class="required">*</span></label>
                                <textarea id="add_topicDesc" class="form-control" rows="4" placeholder="请输入专题描述，最多200字" maxlength="200" required></textarea>
                                <div class="form-hint char-count">
                                    <span id="add_descCharCount">0</span>/200 字
                                </div>
                            </div>

                            <div class="form-group">
                                <label>显示顺序</label>
                                <input type="number" id="add_topicOrder" class="form-control" value="0" min="0" placeholder="数字越小越靠前">
                            </div>
                        </form>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-cancel" onclick="TopicManagementManager.closeAddModal()">取消</button>
                        <button class="btn btn-primary" onclick="TopicManagementManager.saveNewTopic()">
                            <i class="fas fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('addTopicModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 字符计数
        const descTextarea = document.getElementById('add_topicDesc');
        const charCount = document.getElementById('add_descCharCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 关闭新增模态框
    static closeAddModal() {
        const modal = document.getElementById('addTopicModal');
        if (modal) modal.remove();
    }

    // 保存新专题
    static saveNewTopic() {
        const name = document.getElementById('add_topicName').value.trim();
        const desc = document.getElementById('add_topicDesc').value.trim();
        const order = document.getElementById('add_topicOrder').value;

        if (!name) {
            alert('请输入专题名称');
            return;
        }

        if (!desc) {
            alert('请输入专题描述');
            return;
        }

        const topicData = {
            name,
            desc,
            order,
            createTime: new Date().toLocaleString()
        };

        console.log('新增专题数据:', topicData);
        alert('专题创建成功!');
        this.closeAddModal();
    }

    // 显示批量导入模态框
    static showBatchImportModal() {
        const modalHTML = `
            <div class="upload-modal" id="batchImportTopicModal">
                <div class="upload-modal-content" style="max-width: 700px;">
                    <div class="upload-modal-header">
                        <h2><i class="fas fa-file-import"></i> 批量导入专题</h2>
                        <button class="upload-modal-close" onclick="TopicManagementManager.closeBatchImportModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <div class="import-instructions">
                            <h3><i class="fas fa-info-circle"></i> 导入说明</h3>
                            <ul>
                                <li>支持上传 Excel 文件 (.xlsx, .xls) 或 CSV 文件 (.csv)</li>
                                <li>文件大小不超过 5MB</li>
                                <li>请按照模板格式准备数据</li>
                            </ul>
                            <button class="btn btn-secondary" onclick="TopicManagementManager.downloadTemplate()">
                                <i class="fas fa-download"></i> 下载导入模板
                            </button>
                        </div>

                        <div class="upload-area" id="importUploadArea" style="margin-top: 20px;">
                            <input type="file" id="importFileInput" style="display: none;" accept=".xlsx,.xls,.csv">
                            <div class="upload-placeholder">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <h3>点击或拖拽文件到此处上传</h3>
                                <p class="upload-hint">支持 Excel (.xlsx, .xls) 和 CSV (.csv) 格式</p>
                            </div>
                        </div>

                        <div class="import-preview" id="importPreview" style="display: none; margin-top: 20px;">
                            <h3>数据预览</h3>
                            <div class="preview-table-container">
                                <table id="previewTable" class="preview-table">
                                    <thead>
                                        <tr>
                                            <th>专题名称</th>
                                            <th>专题描述</th>
                                            <th>状态</th>
                                        </tr>
                                    </thead>
                                    <tbody id="previewTableBody"></tbody>
                                </table>
                            </div>
                            <div class="import-summary" id="importSummary"></div>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-cancel" onclick="TopicManagementManager.closeBatchImportModal()">取消</button>
                        <button class="btn btn-primary" id="confirmImportBtn" style="display: none;" onclick="TopicManagementManager.confirmImport()">
                            <i class="fas fa-check"></i> 确认导入
                        </button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('batchImportTopicModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        this.initBatchImport();
    }

    // 初始化批量导入
    static initBatchImport() {
        const uploadArea = document.getElementById('importUploadArea');
        const fileInput = document.getElementById('importFileInput');

        uploadArea.addEventListener('click', () => fileInput.click());

        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                TopicManagementManager.handleImportFile(file);
            }
        });

        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('drag-over');
        });

        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
            const file = e.dataTransfer.files[0];
            if (file) {
                TopicManagementManager.handleImportFile(file);
            }
        });
    }

    // 处理导入文件
    static handleImportFile(file) {
        const fileName = file.name.toLowerCase();
        const validExtensions = ['.xlsx', '.xls', '.csv'];
        const isValid = validExtensions.some(ext => fileName.endsWith(ext));

        if (!isValid) {
            alert('仅支持 Excel (.xlsx, .xls) 和 CSV (.csv) 格式的文件');
            return;
        }

        if (file.size > 5 * 1024 * 1024) {
            alert('文件大小不能超过 5MB');
            return;
        }

        // 模拟解析数据
        const mockData = [
            { name: '税务基础知识', desc: '涵盖税务相关的基础知识和常见问题', status: '已发布' },
            { name: '客服沟通技巧', desc: '提升客服人员沟通能力的专题', status: '已发布' },
            { name: '业务流程指南', desc: '详细的业务操作流程说明', status: '草稿' }
        ];

        this.showImportPreview(mockData);
    }

    // 显示导入预览
    static showImportPreview(data) {
        const preview = document.getElementById('importPreview');
        const tbody = document.getElementById('previewTableBody');
        const summary = document.getElementById('importSummary');
        const confirmBtn = document.getElementById('confirmImportBtn');

        preview.style.display = 'block';
        confirmBtn.style.display = 'inline-flex';

        tbody.innerHTML = data.map(item => `
            <tr>
                <td>${item.name}</td>
                <td>${item.desc}</td>
                <td><span class="status-badge ${item.status === '已发布' ? 'status-published' : 'status-draft'}">${item.status}</span></td>
            </tr>
        `).join('');

        summary.innerHTML = `
            <div class="summary-item">
                <i class="fas fa-check-circle" style="color: #28a745;"></i>
                共解析 ${data.length} 条数据，准备导入
            </div>
        `;

        window.importData = data;
    }

    // 确认导入
    static confirmImport() {
        if (!window.importData || window.importData.length === 0) {
            alert('没有可导入的数据');
            return;
        }

        console.log('导入数据:', window.importData);
        alert(`成功导入 ${window.importData.length} 个专题!`);
        this.closeBatchImportModal();
        window.importData = null;
    }

    // 下载模板
    static downloadTemplate() {
        alert('正在下载导入模板...\n\n模板包含以下列:\n- 专题名称（必填）\n- 专题描述（必填）\n- 状态（已发布/草稿）\n- 显示顺序');
    }

    // 关闭批量导入模态框
    static closeBatchImportModal() {
        const modal = document.getElementById('batchImportTopicModal');
        if (modal) modal.remove();
        window.importData = null;
    }

    // 显示专题详情
    static showDetailModal(topicId) {
        const mockData = {
            'TP001': {
                id: 'TP001',
                name: '新手入门指南',
                desc: '帮助新用户快速上手系统',
                icon: 'fa-graduation-cap',
                order: 1,
                resourceCount: 15,
                viewCount: 1234,
                creator: 'admin',
                status: '已发布',
                createTime: '2024-01-10 10:30:00',
                updateTime: '2024-01-15 10:30:00',
                resources: [
                    { id: 'RS001', title: '系统登录指南' },
                    { id: 'RS002', title: '基础功能介绍' },
                    { id: 'RS003', title: '常见问题解答' }
                ]
            },
            'TP002': {
                id: 'TP002',
                name: '高级功能教程',
                desc: '系统高级功能使用说明',
                icon: 'fa-rocket',
                order: 2,
                resourceCount: 23,
                viewCount: 856,
                creator: 'admin',
                status: '已发布',
                createTime: '2024-01-08 14:20:00',
                updateTime: '2024-01-12 14:20:00',
                resources: [
                    { id: 'RS010', title: '高级搜索技巧' },
                    { id: 'RS011', title: '批量操作指南' }
                ]
            }
        };

        const data = mockData[topicId] || mockData['TP001'];

        const modalHTML = `
            <div class="upload-modal" id="topicDetailModal">
                <div class="upload-modal-content" style="max-width: 900px;">
                    <div class="upload-modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                        <h2 style="color: white;"><i class="fas fa-eye"></i> 专题详情</h2>
                        <button class="upload-modal-close" onclick="TopicManagementManager.closeDetailModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body" style="max-height: 70vh; overflow-y: auto;">
                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-info-circle"></i> 基本信息</h3>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <label>专题编号:</label>
                                    <div>${data.id}</div>
                                </div>
                                <div class="detail-item">
                                    <label>专题名称:</label>
                                    <div>${data.name}</div>
                                </div>
                                <div class="detail-item">
                                    <label>显示顺序:</label>
                                    <div>${data.order}</div>
                                </div>
                                <div class="detail-item">
                                    <label>包含资源数:</label>
                                    <div>${data.resourceCount}</div>
                                </div>
                                <div class="detail-item">
                                    <label>浏览次数:</label>
                                    <div>${data.viewCount}</div>
                                </div>
                                <div class="detail-item">
                                    <label>创建人:</label>
                                    <div>${data.creator}</div>
                                </div>
                            </div>
                        </div>

                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-align-left"></i> 专题描述</h3>
                            <div class="detail-description">${data.desc}</div>
                        </div>

                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-book"></i> 关联资源 (${data.resources.length})</h3>
                            <div class="resource-list-detail">
                                ${data.resources.map((res, index) => `
                                    <div class="resource-item">
                                        <span class="resource-index">${index + 1}</span>
                                        <span class="resource-id">${res.id}</span>
                                        <span class="resource-title">${res.title}</span>
                                    </div>
                                `).join('')}
                            </div>
                        </div>

                        <div class="detail-section">
                            <h3 class="detail-section-title"><i class="fas fa-clock"></i> 时间信息</h3>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <label>创建时间:</label>
                                    <div>${data.createTime}</div>
                                </div>
                                <div class="detail-item">
                                    <label>更新时间:</label>
                                    <div>${data.updateTime}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-primary" onclick="TopicManagementManager.showEditModal('${data.id}'); TopicManagementManager.closeDetailModal();">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-cancel" onclick="TopicManagementManager.closeDetailModal()">关闭</button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('topicDetailModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }

    // 关闭详情模态框
    static closeDetailModal() {
        const modal = document.getElementById('topicDetailModal');
        if (modal) modal.remove();
    }

    // 显示编辑专题模态框
    static showEditModal(topicId) {
        const mockData = {
            'TP001': {
                id: 'TP001',
                name: '新手入门指南',
                desc: '帮助新用户快速上手系统',
                icon: 'fa-graduation-cap',
                order: 1,
                status: '已发布'
            },
            'TP002': {
                id: 'TP002',
                name: '高级功能教程',
                desc: '系统高级功能使用说明',
                icon: 'fa-rocket',
                order: 2,
                status: '已发布'
            }
        };

        const data = mockData[topicId] || mockData['TP001'];

        const modalHTML = `
            <div class="upload-modal" id="editTopicModal">
                <div class="upload-modal-content" style="max-width: 800px;">
                    <div class="upload-modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                        <h2 style="color: white;"><i class="fas fa-edit"></i> 编辑专题</h2>
                        <button class="upload-modal-close" onclick="TopicManagementManager.closeEditModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <form id="editTopicForm">
                            <div class="form-section-title">
                                <i class="fas fa-info-circle"></i> 基本信息
                            </div>

                            <div class="form-group">
                                <label>专题名称 <span class="required">*</span></label>
                                <input type="text" id="edit_topicName" class="form-control" value="${data.name}" required>
                            </div>

                            <div class="form-group">
                                <label>专题描述 <span class="required">*</span></label>
                                <textarea id="edit_topicDesc" class="form-control" rows="4" maxlength="200" required>${data.desc}</textarea>
                                <div class="form-hint char-count">
                                    <span id="edit_descCharCount">${data.desc.length}</span>/200 字
                                </div>
                            </div>

                            <div class="form-group">
                                <label>显示顺序</label>
                                <input type="number" id="edit_topicOrder" class="form-control" value="${data.order}" min="0" placeholder="数字越小越靠前">
                            </div>

                            <input type="hidden" id="edit_topicId" value="${data.id}">
                        </form>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-primary" onclick="TopicManagementManager.saveEditTopic()">
                            <i class="fas fa-save"></i> 保存更改
                        </button>
                        <button class="btn btn-cancel" onclick="TopicManagementManager.closeEditModal()">取消</button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('editTopicModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 字符计数
        const descTextarea = document.getElementById('edit_topicDesc');
        const charCount = document.getElementById('edit_descCharCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 关闭编辑模态框
    static closeEditModal() {
        const modal = document.getElementById('editTopicModal');
        if (modal) modal.remove();
    }

    // 保存编辑
    static saveEditTopic() {
        const topicId = document.getElementById('edit_topicId').value;
        const name = document.getElementById('edit_topicName').value.trim();
        const desc = document.getElementById('edit_topicDesc').value.trim();
        const order = document.getElementById('edit_topicOrder').value;

        if (!name) {
            alert('请输入专题名称');
            return;
        }

        if (!desc) {
            alert('请输入专题描述');
            return;
        }

        const topicData = {
            id: topicId,
            name,
            desc,
            order
        };

        console.log('更新专题数据:', topicData);
        alert(`专题 ${topicId} 更新成功!`);
        this.closeEditModal();
    }

    // 删除专题
    static deleteTopic(topicId) {
        if (!confirm(`确定要删除专题 ${topicId} 吗?\n此操作不可恢复!`)) {
            return;
        }

        console.log('删除专题:', topicId);
        alert(`专题 ${topicId} 已删除`);
    }

    // 批量删除
    static batchDelete(container) {
        const checkedBoxes = container.querySelectorAll('.rowCheckbox:checked');

        if (checkedBoxes.length === 0) {
            alert('请至少选择一个专题进行删除');
            return;
        }

        const topicIds = [];
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            const topicId = row.cells[1].textContent;
            topicIds.push(topicId);
        });

        const confirmMsg = `确定要删除选中的 ${topicIds.length} 个专题吗?\n此操作不可恢复!`;
        if (!confirm(confirmMsg)) return;

        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            row.remove();
        });

        const selectAll = container.querySelector('#selectAllTopics');
        if (selectAll) selectAll.checked = false;

        alert(`已成功删除 ${topicIds.length} 个专题`);
    }

    // 选择资源（用于关联资源）
    static selectResources() {
        alert('打开资源选择器...\n\n这里可以选择要关联到专题的资源');
    }

    // ========== 专题查询功能 ==========

    // 执行专题查询
    static executeTopicSearch(container) {
        // 获取查询条件
        const searchCriteria = {
            topicId: document.getElementById('topic_search_id')?.value.trim() || '',
            topicName: document.getElementById('topic_search_name')?.value.trim() || '',
            creator: document.getElementById('topic_search_creator')?.value.trim() || '',
            updateTimeStart: document.getElementById('topic_search_updateTimeStart')?.value || '',
            updateTimeEnd: document.getElementById('topic_search_updateTimeEnd')?.value || ''
        };

        console.log('专题查询条件:', searchCriteria);

        // 模拟专题数据
        const allTopics = [
            {
                id: 'TP001',
                name: '新手入门指南',
                desc: '帮助新用户快速上手系统',
                resourceCount: 15,
                viewCount: 1234,
                creator: 'admin',
                updateTime: '2024-01-15 10:30:00'
            },
            {
                id: 'TP002',
                name: '高级功能教程',
                desc: '系统高级功能使用说明',
                resourceCount: 23,
                viewCount: 856,
                creator: 'admin',
                updateTime: '2024-01-12 14:20:00'
            },
            {
                id: 'TP003',
                name: '税务政策解读',
                desc: '最新税务政策详细解读',
                resourceCount: 8,
                viewCount: 432,
                creator: 'editor',
                updateTime: '2024-01-10 09:15:00'
            },
            {
                id: 'TP004',
                name: '客服技巧培训',
                desc: '提升客服人员专业能力',
                resourceCount: 12,
                viewCount: 678,
                creator: 'trainer',
                updateTime: '2023-12-28 16:45:00'
            }
        ];

        // 筛选逻辑
        let filteredTopics = allTopics.filter(topic => {
            // 专题编号模糊查询
            if (searchCriteria.topicId && !topic.id.toLowerCase().includes(searchCriteria.topicId.toLowerCase())) {
                return false;
            }

            // 专题名称模糊查询
            if (searchCriteria.topicName && !topic.name.includes(searchCriteria.topicName)) {
                return false;
            }

            // 创建人精确查询
            if (searchCriteria.creator && topic.creator !== searchCriteria.creator) {
                return false;
            }

            // 更新时间范围查询
            if (searchCriteria.updateTimeStart || searchCriteria.updateTimeEnd) {
                const updateTime = new Date(topic.updateTime);
                if (searchCriteria.updateTimeStart) {
                    const startTime = new Date(searchCriteria.updateTimeStart);
                    if (updateTime < startTime) return false;
                }
                if (searchCriteria.updateTimeEnd) {
                    const endTime = new Date(searchCriteria.updateTimeEnd);
                    endTime.setHours(23, 59, 59, 999);
                    if (updateTime > endTime) return false;
                }
            }

            return true;
        });

        console.log('筛选结果:', filteredTopics);

        // 更新表格显示
        this.updateTopicTable(container, filteredTopics);

        // 显示搜索结果提示
        alert(`查询完成！找到 ${filteredTopics.length} 个匹配的专题`);
    }

    // 更新专题表格
    static updateTopicTable(container, topics) {
        const tbody = container.querySelector('table tbody');
        if (!tbody) return;

        if (topics.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="9" style="text-align: center; padding: 40px; color: #999;">
                        <i class="fas fa-search" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                        未找到符合条件的专题
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = topics.map(topic => `
            <tr>
                <td><input type="checkbox" class="rowCheckbox"></td>
                <td>${topic.id}</td>
                <td>${topic.name}</td>
                <td>${topic.desc}</td>
                <td>${topic.resourceCount}</td>
                <td>${topic.viewCount}</td>
                <td>${topic.creator}</td>
                <td>${topic.updateTime}</td>
                <td class="operation">
                    <a href="#" onclick="TopicManagementManager.showDetailModal('${topic.id}'); return false;"><i class="fas fa-eye"></i> 查看</a>
                    <a href="#" onclick="TopicManagementManager.showEditModal('${topic.id}'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                    <a href="#" onclick="TopicManagementManager.deleteTopic('${topic.id}'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                </td>
            </tr>
        `).join('');
    }

    // 重置专题查询
    static resetTopicSearch(container) {
        document.getElementById('topic_search_id').value = '';
        document.getElementById('topic_search_name').value = '';
        document.getElementById('topic_search_creator').value = '';
        document.getElementById('topic_search_updateTimeStart').value = '';
        document.getElementById('topic_search_updateTimeEnd').value = '';

        alert('查询条件已重置');

        // 重新加载全部专题
        this.executeTopicSearch(container);
    }
}

// 知识库管理模块 - 标签管理
class TagManagementManager {
    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                管理知识库标签，通过标签体系实现知识的灵活分类和快速检索。
            </div>

            <div class="actions">
                <button class="btn-primary btn-add-tag"><i class="fas fa-plus"></i> 新增标签</button>
                <button class="btn btn-export"><i class="fas fa-file-export"></i> 导出</button>
                <button class="btn btn-delete" id="batchDeleteTagsBtn"><i class="fas fa-trash-alt"></i> 批量删除</button>
            </div>

            <!-- 查询条件区域 -->
            <div class="tag-search-area">
                <div class="search-form-row">
                    <div class="search-form-group">
                        <label>标签ID</label>
                        <input type="text" id="tag_search_id" class="form-control" placeholder="输入标签ID，支持模糊查询">
                    </div>
                    <div class="search-form-group">
                        <label>标签名称</label>
                        <input type="text" id="tag_search_name" class="form-control" placeholder="输入标签名称，支持模糊查询">
                    </div>
                    <div class="search-form-group">
                        <label>创建人</label>
                        <input type="text" id="tag_search_creator" class="form-control" placeholder="输入创建人">
                    </div>
                </div>

                <div class="search-form-row">
                    <div class="search-form-group">
                        <label>更新时间</label>
                        <div class="date-range-group">
                            <input type="date" id="tag_search_updateTimeStart" class="form-control">
                            <span class="date-separator">至</span>
                            <input type="date" id="tag_search_updateTimeEnd" class="form-control">
                        </div>
                    </div>
                    <div class="search-form-group search-actions">
                        <button class="btn btn-primary" id="tagSearchBtn"><i class="fas fa-search"></i> 查询</button>
                        <button class="btn btn-secondary" id="tagResetBtn"><i class="fas fa-redo"></i> 重置</button>
                    </div>
                </div>
            </div>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllTags"></th>
                            <th>标签ID</th>
                            <th>标签名称</th>
                            <th>关联资源数</th>
                            <th>创建人</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>TAG001</td>
                            <td>个税扣除</td>
                            <td>25</td>
                            <td>admin</td>
                            <td>2024-01-15 10:30:00</td>
                            <td class="operation">
                                <a href="#" onclick="TagManagementManager.showEditModal('TAG001'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" onclick="TagManagementManager.deleteTag('TAG001'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>TAG002</td>
                            <td>专项附加</td>
                            <td>18</td>
                            <td>admin</td>
                            <td>2024-01-12 14:20:00</td>
                            <td class="operation">
                                <a href="#" onclick="TagManagementManager.showEditModal('TAG002'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" onclick="TagManagementManager.deleteTag('TAG002'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>TAG003</td>
                            <td>客服话术</td>
                            <td>12</td>
                            <td>admin</td>
                            <td>2024-01-10 09:15:00</td>
                            <td class="operation">
                                <a href="#" onclick="TagManagementManager.showEditModal('TAG003'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" onclick="TagManagementManager.deleteTag('TAG003'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">下一页</a>
            </div>
        `;

        // 设置全选功能
        const selectAll = container.querySelector('#selectAllTags');
        if (selectAll) {
            selectAll.addEventListener('change', function() {
                const checkboxes = container.querySelectorAll('.rowCheckbox');
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        }

        // 绑定新增标签按钮
        const addTagBtn = container.querySelector('.btn-add-tag');
        if (addTagBtn) {
            addTagBtn.addEventListener('click', function() {
                TagManagementManager.showAddModal();
            });
        }

        // 绑定批量删除按钮
        const batchDeleteBtn = container.querySelector('#batchDeleteTagsBtn');
        if (batchDeleteBtn) {
            batchDeleteBtn.addEventListener('click', function() {
                TagManagementManager.batchDelete(container);
            });
        }

        // 绑定查询按钮
        const tagSearchBtn = container.querySelector('#tagSearchBtn');
        if (tagSearchBtn) {
            tagSearchBtn.addEventListener('click', function() {
                TagManagementManager.executeTagSearch(container);
            });
        }

        // 绑定重置按钮
        const tagResetBtn = container.querySelector('#tagResetBtn');
        if (tagResetBtn) {
            tagResetBtn.addEventListener('click', function() {
                TagManagementManager.resetTagSearch(container);
            });
        }
    }

    // 显示新增标签模态框
    static showAddModal() {
        const modalHTML = `
            <div class="upload-modal" id="addTagModal">
                <div class="upload-modal-content" style="max-width: 600px;">
                    <div class="upload-modal-header">
                        <h2><i class="fas fa-plus-circle"></i> 新增标签</h2>
                        <button class="upload-modal-close" onclick="TagManagementManager.closeAddModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <form id="addTagForm">
                            <div class="form-section-title">
                                <i class="fas fa-info-circle"></i> 标签信息
                            </div>

                            <div class="form-group">
                                <label>标签名称 <span class="required">*</span></label>
                                <input type="text" id="add_tagName" class="form-control" placeholder="请输入标签名称" required>
                            </div>

                            <div class="form-group">
                                <label>标签描述</label>
                                <textarea id="add_tagDesc" class="form-control" rows="3" placeholder="请输入标签描述，最多100字" maxlength="100"></textarea>
                                <div class="form-hint char-count">
                                    <span id="add_tagDescCharCount">0</span>/100 字
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-cancel" onclick="TagManagementManager.closeAddModal()">取消</button>
                        <button class="btn btn-primary" onclick="TagManagementManager.saveNewTag()">
                            <i class="fas fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('addTagModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 字符计数
        const descTextarea = document.getElementById('add_tagDesc');
        const charCount = document.getElementById('add_tagDescCharCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 关闭新增模态框
    static closeAddModal() {
        const modal = document.getElementById('addTagModal');
        if (modal) modal.remove();
    }

    // 保存新标签
    static saveNewTag() {
        const name = document.getElementById('add_tagName').value.trim();
        const desc = document.getElementById('add_tagDesc').value.trim();

        if (!name) {
            alert('请输入标签名称');
            return;
        }

        const tagData = {
            name,
            desc,
            createTime: new Date().toLocaleString()
        };

        console.log('新增标签数据:', tagData);
        alert('标签创建成功!');
        this.closeAddModal();
    }

    // 显示编辑标签模态框
    static showEditModal(tagId) {
        const mockData = {
            'TAG001': {
                id: 'TAG001',
                name: '个税扣除',
                desc: '个人所得税专项附加扣除相关内容'
            },
            'TAG002': {
                id: 'TAG002',
                name: '专项附加',
                desc: '税务专项附加扣除政策'
            },
            'TAG003': {
                id: 'TAG003',
                name: '客服话术',
                desc: '客服沟通话术和技巧'
            }
        };

        const data = mockData[tagId] || mockData['TAG001'];

        const modalHTML = `
            <div class="upload-modal" id="editTagModal">
                <div class="upload-modal-content" style="max-width: 600px;">
                    <div class="upload-modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                        <h2 style="color: white;"><i class="fas fa-edit"></i> 编辑标签</h2>
                        <button class="upload-modal-close" onclick="TagManagementManager.closeEditModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="upload-modal-body">
                        <form id="editTagForm">
                            <div class="form-section-title">
                                <i class="fas fa-info-circle"></i> 标签信息
                            </div>

                            <div class="form-group">
                                <label>标签名称 <span class="required">*</span></label>
                                <input type="text" id="edit_tagName" class="form-control" value="${data.name}" required>
                            </div>

                            <div class="form-group">
                                <label>标签描述</label>
                                <textarea id="edit_tagDesc" class="form-control" rows="3" maxlength="100">${data.desc || ''}</textarea>
                                <div class="form-hint char-count">
                                    <span id="edit_tagDescCharCount">${(data.desc || '').length}</span>/100 字
                                </div>
                            </div>

                            <input type="hidden" id="edit_tagId" value="${data.id}">
                        </form>
                    </div>

                    <div class="upload-modal-footer">
                        <button class="btn btn-primary" onclick="TagManagementManager.saveEditTag()">
                            <i class="fas fa-save"></i> 保存更改
                        </button>
                        <button class="btn btn-cancel" onclick="TagManagementManager.closeEditModal()">取消</button>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('editTagModal');
        if (existingModal) existingModal.remove();
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // 字符计数
        const descTextarea = document.getElementById('edit_tagDesc');
        const charCount = document.getElementById('edit_tagDescCharCount');
        if (descTextarea && charCount) {
            descTextarea.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    }

    // 关闭编辑模态框
    static closeEditModal() {
        const modal = document.getElementById('editTagModal');
        if (modal) modal.remove();
    }

    // 保存编辑标签
    static saveEditTag() {
        const tagId = document.getElementById('edit_tagId').value;
        const name = document.getElementById('edit_tagName').value.trim();
        const desc = document.getElementById('edit_tagDesc').value.trim();

        if (!name) {
            alert('请输入标签名称');
            return;
        }

        const tagData = {
            id: tagId,
            name,
            desc
        };

        console.log('更新标签数据:', tagData);
        alert(`标签 ${tagId} 更新成功!`);
        this.closeEditModal();
    }

    // 删除标签
    static deleteTag(tagId) {
        if (!confirm(`确定要删除标签 ${tagId} 吗?\n此操作不可恢复!`)) {
            return;
        }

        console.log('删除标签:', tagId);
        alert(`标签 ${tagId} 已删除`);
    }

    // 批量删除
    static batchDelete(container) {
        const checkedBoxes = container.querySelectorAll('.rowCheckbox:checked');

        if (checkedBoxes.length === 0) {
            alert('请至少选择一个标签进行删除');
            return;
        }

        const tagIds = [];
        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            const tagId = row.cells[1].textContent;
            tagIds.push(tagId);
        });

        const confirmMsg = `确定要删除选中的 ${tagIds.length} 个标签吗?\n此操作不可恢复!`;
        if (!confirm(confirmMsg)) return;

        checkedBoxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            row.remove();
        });

        const selectAll = container.querySelector('#selectAllTags');
        if (selectAll) selectAll.checked = false;

        alert(`已成功删除 ${tagIds.length} 个标签`);
    }

    // ========== 标签查询功能 ==========

    // 执行标签查询
    static executeTagSearch(container) {
        // 获取查询条件
        const searchCriteria = {
            tagId: document.getElementById('tag_search_id')?.value.trim() || '',
            tagName: document.getElementById('tag_search_name')?.value.trim() || '',
            creator: document.getElementById('tag_search_creator')?.value.trim() || '',
            updateTimeStart: document.getElementById('tag_search_updateTimeStart')?.value || '',
            updateTimeEnd: document.getElementById('tag_search_updateTimeEnd')?.value || ''
        };

        console.log('标签查询条件:', searchCriteria);

        // 模拟标签数据
        const allTags = [
            {
                id: 'TAG001',
                name: '个税扣除',
                resourceCount: 25,
                creator: 'admin',
                updateTime: '2024-01-15 10:30:00'
            },
            {
                id: 'TAG002',
                name: '专项附加',
                resourceCount: 18,
                creator: 'admin',
                updateTime: '2024-01-12 14:20:00'
            },
            {
                id: 'TAG003',
                name: '客服话术',
                resourceCount: 12,
                creator: 'admin',
                updateTime: '2024-01-10 09:15:00'
            },
            {
                id: 'TAG004',
                name: '税务咨询',
                resourceCount: 22,
                creator: 'editor',
                updateTime: '2024-01-08 16:45:00'
            },
            {
                id: 'TAG005',
                name: '增值税',
                resourceCount: 15,
                creator: 'admin',
                updateTime: '2023-12-28 11:20:00'
            }
        ];

        // 筛选逻辑
        let filteredTags = allTags.filter(tag => {
            // 标签ID模糊查询
            if (searchCriteria.tagId && !tag.id.toLowerCase().includes(searchCriteria.tagId.toLowerCase())) {
                return false;
            }

            // 标签名称模糊查询
            if (searchCriteria.tagName && !tag.name.includes(searchCriteria.tagName)) {
                return false;
            }

            // 创建人精确查询
            if (searchCriteria.creator && tag.creator !== searchCriteria.creator) {
                return false;
            }

            // 更新时间范围查询
            if (searchCriteria.updateTimeStart || searchCriteria.updateTimeEnd) {
                const updateTime = new Date(tag.updateTime);
                if (searchCriteria.updateTimeStart) {
                    const startTime = new Date(searchCriteria.updateTimeStart);
                    if (updateTime < startTime) return false;
                }
                if (searchCriteria.updateTimeEnd) {
                    const endTime = new Date(searchCriteria.updateTimeEnd);
                    endTime.setHours(23, 59, 59, 999);
                    if (updateTime > endTime) return false;
                }
            }

            return true;
        });

        console.log('筛选结果:', filteredTags);

        // 更新表格显示
        this.updateTagTable(container, filteredTags);

        // 显示搜索结果提示
        alert(`查询完成！找到 ${filteredTags.length} 个匹配的标签`);
    }

    // 更新标签表格
    static updateTagTable(container, tags) {
        const tbody = container.querySelector('table tbody');
        if (!tbody) return;

        if (tags.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
                        <i class="fas fa-search" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                        未找到符合条件的标签
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = tags.map(tag => `
            <tr>
                <td><input type="checkbox" class="rowCheckbox"></td>
                <td>${tag.id}</td>
                <td>${tag.name}</td>
                <td>${tag.resourceCount}</td>
                <td>${tag.creator}</td>
                <td>${tag.updateTime}</td>
                <td class="operation">
                    <a href="#" onclick="TagManagementManager.showEditModal('${tag.id}'); return false;"><i class="fas fa-edit"></i> 编辑</a>
                    <a href="#" onclick="TagManagementManager.deleteTag('${tag.id}'); return false;" class="text-danger"><i class="fas fa-trash"></i> 删除</a>
                </td>
            </tr>
        `).join('');
    }

    // 重置标签查询
    static resetTagSearch(container) {
        document.getElementById('tag_search_id').value = '';
        document.getElementById('tag_search_name').value = '';
        document.getElementById('tag_search_creator').value = '';
        document.getElementById('tag_search_updateTimeStart').value = '';
        document.getElementById('tag_search_updateTimeEnd').value = '';

        alert('查询条件已重置');

        // 重新加载全部标签
        this.executeTagSearch(container);
    }
}
